html页中的python抓取日期(2017年6月10日) [英] python scraping date from html page (June 10, 2017)

查看:52
本文介绍了html页中的python抓取日期(2017年6月10日)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从具有以下表格数据的html页中提取日期"2017年6月3日".日期将根据订单号更改.我不确定我是否使用正确.请指教.

How can I extract date "June 03,2017" from html page having below table data. The date will change as per the order number. I am not sure if i am using it correctly. please advise.

<tr>
   <td style="font:bold 24px Arial;">Order #12345</td>
    <td style="font:13px Arial;"><strong>Order Date:</strong> June 03, 2017</td>
</tr>

下面是我编写的示例代码

Below is the sample code which i have written

import requests
from bs4 import BeautifulSoup

#'url' is the actual link of html page
data = requests.get('url').content
soup = BeautifulSoup(data, "html.parser")

on = soup.find_all(text=re.compile("Order #"))
print (on)

od = soup.find_all(text=re.compile("Order Date")).next_element()
print (od)

执行上面的代码后,我得到下面的错误.

I am getting below error after executing above code.

Error :
['Order #12345']
Traceback (most recent call last):
  File "test.py", line 24, in <module>
    od = soup.find_all(text=re.compile("Order Date")).next_element()
AttributeError: 'ResultSet' object has no attribute 'next_element'

推荐答案

或者,

>>> import requests
>>> import bs4
>>> soup = bs4.BeautifulSoup('''\
... <tr>
...     <td style="font:bold 24px Arial;">Order #12345</td>
...     <td style="font:13px Arial;"><strong>Order Date:</strong> June 03, 2017</td>
... </tr>''', 'lxml')
>>> soup.find_all(text=bs4.re.compile("Order #"))[0][7:]
'12345'
>>> soup.find_all(text=bs4.re.compile("Order Date:"))[0].parent.next.next.strip()
'June 03, 2017'

由于bs4中包含import re,因此无需单独进行操作.我按照你的所作所为.也就是说,我查找了文本,然后从那里导航.

No need to import re separately as it is include in bs4. I followed what you did; that is, I looked for the text then navigated from there.

这篇关于html页中的python抓取日期(2017年6月10日)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆