【问题标题】:bs4 cannot pick expected text string?bs4 无法选择预期的文本字符串?
【发布时间】:2016-10-05 21:56:34
【问题描述】:

我想使用 bs4 提取文章的发布日期,因为报纸模块有时可以工作,而在其他情况下则不能。

例如,网址是http://www.popsci.com/ups-tests-drone-deliveries-to-island

from bs4 import BeautifulSoup
import urllib.request

page = urllib.request.urlopen(url)
soup = BeautifulSoup(page, 'lxml')

#print (soup.prettify())
date = soup.find('span', {'class':"date"})
print (date)

这将显示以下信息。

<span class="date" data-timestamp="1474907692"><span class="label">posted</span> Sep 26th, 2016 at 12:34pm</span>

我只需要 2016 年 9 月 26 日下午 12:34 份。

所以,我试过了,

date = soup.find('span',{'class':"date"}, text=(re.compile("Sep")))

但是,这只会返回 None

我相信我在这里错过了一些东西,但不知道出了什么问题。 有人可以帮助我指导我应该解决的问题吗?

【问题讨论】:

  • 类中你要的文字不是叫“label”吗?

标签: regex python-3.x web-scraping bs4


【解决方案1】:

怎么样:

date = soup.find('span', {'class':"date"}).text.replace("posted ", "")
# 'Sep 26th, 2016 at 12:34pm'

您可能希望将其包装到某个 try/catch 块中以使其更安全。

【讨论】:

  • 谢谢。有用。我想更进一步。我想让这个日期提取语句尽可能通用,以便我可以将它重用于其他页面抓取。所以,我试过了, date = soup.find('span', text=re.compile(r"^Sep$|^Sept|^SEP$")) 但是,这不起作用.. 只是返回 None 再次。这里最好的方法是什么?
猜你喜欢
  • 2012-08-30
  • 2022-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多