beautifulsoup find_all bug?

时间:2015-02-11 05:59:45

标签: beautifulsoup findall

现在我正在用漂亮的汤来解析html页面。但有时我通过find_all获得的结果小于页面中的数字。例如,此页面http://www.totallyfreestuff.com/index.asp?m=0&sb=1&p=5有18个标题范围。但是,当我使用以下代码时,它只有两个!任何人都可以告诉我原因。提前谢谢!

soup = BeautifulSoup(page, 'html.parser')
hrefDivList = soup.find_all("span", class_ = "headline")
#print hrefDivList
print len(hrefDivList)

2 个答案:

答案 0 :(得分:1)

您可以尝试为Beautifulsoup使用不同的解析器。

import requests
from bs4 import BeautifulSoup

url = "<your url>"
r = requests.get(url)

soup = BeautifulSoup(r.content, 'lxml')
hrefDivList = soup.find_all("span", attrs={"class": "headline"})
print len(hrefDivList)

答案 1 :(得分:0)

您可以尝试使用CSS选择器让您的生活更轻松

hrefDivList = soup.select("span.headline")
#print hrefDivList
print len(hrefDivList)

或者您可以直接遍历每个Span文本

for every_span in soup.select("span.headline"):
    print(every_span.text)
相关问题