【问题标题】:Extracting <a> tags using BeautifulSoup使用 BeautifulSoup 提取 <a> 标签
【发布时间】:2016-04-01 06:48:44
【问题描述】:

我在从https://www.symantec.com/index.jsp 中提取“a”标签时遇到问题。

以下是代码,它给了我一组空的“链接”。

from bs4 import BeautifulSoup
import urllib2

response = urllib2.urlopen('https://www.symantec.com/index.jsp').read()
soup = BeautifulSoup(response, 'html.parser')
links = soup.find_all('a')
print(links)

对于其他 url,该代码可以正常工作,但它不适用于这个。是因为 index.jsp 是动态的吗?解决方案可能是什么?

我正在使用 python 2.7。

【问题讨论】:

  • https://www.symantec.com/index.jsp 之间有一个空格,也许删除它可以解决您的问题?
  • 尝试使用 python 请求来获取 html...它真的很好用。
  • @hd1 修复了空间,这显然是一个错字。谢谢。
  • @Rhea 是 OP,alecxe,可能不是错字。

标签: python python-2.7 beautifulsoup web-crawler


【解决方案1】:

将解析器更改为html5liblxml

soup = BeautifulSoup(response, 'html5lib')
soup = BeautifulSoup(response, 'lxml')

这需要html5liblxml to be installed:

pip install html5lib
pip install lxml

证明:

>>> from bs4 import BeautifulSoup
>>> import urllib2
>>> 
>>> response = urllib2.urlopen('https://www.symantec.com/index.jsp').read()
>>> len(BeautifulSoup(response, 'html.parser').find_all("a"))
0
>>> len(BeautifulSoup(response, 'html5lib').find_all("a"))
187
>>> len(BeautifulSoup(response, 'lxml').find_all("a"))
187

另请参阅文档的相关部分:

【讨论】:

  • 为什么?其他解析器有什么不同
  • 我评论中的那个问题的意思是“你需要在回答中解释这一点”。
  • 此外,由于您只对文档的一部分感兴趣,您可以创建一个鲜为人知的 SoupStrainer 对象并将其作为 parse_only 参数传递以节省时间和内存。
  • @user3100115 是的,很好,这很容易导致过早的优化问题:)
猜你喜欢
  • 2021-12-22
  • 2022-01-13
  • 2020-10-21
  • 1970-01-01
  • 1970-01-01
  • 2022-06-27
  • 1970-01-01
  • 2021-12-05
  • 2014-06-16
相关资源
最近更新 更多