美汤找不到我想要的HTML部分



我已经使用BeautifulSoup进行网页抓取一段时间了,这是我第一次遇到这样的问题。我正在尝试在代码中选择数字 101,172,但即使我使用 .find 或 .select,输出也始终只是标签,而不是数字。我以前使用过类似的数据收集,没有任何问题

<div class="legend-block legend-block--pageviews">
<h5>Pageviews</h5><hr>
<div class="legend-block--body">
<div class="linear-legend--counts">
Pageviews:
<span class="pull-right">
101,172
</span>
</div>
<div class="linear-legend--counts">
Daily average:
<span class="pull-right">
4,818
</span>
</div></div></div>

我使用过:

res = requests.get(wiki_page, timeout =None)
soup = bs4.BeautifulSoup(res.text, 'html.parser')
ab=soup.select('span[class="pull-right"]')
#print(i)
print(ab)

输出:

[<span class="pull-right">n<label class="logarithmic-scale">n<input 
class="logarithmic-scale-option" type="checkbox"/>n        Logarithmic scale      
</label>n</span>, <span class="pull-right">n<label class="begin-at- 
zero">n<input class="begin-at-zero-option" type="checkbox"/>n        Begin at 
zero      </label>n</span>, <span class="pull-right">n<label class="show- 
labels">n<input class="show-labels-option" type="checkbox"/>n        Show 
values      </label>n</span>]

此外,我正在寻找的数据编号是动态的,所以我不确定Javascript是否会影响BeautifulSoup。

试试这个:

from bs4 import BeautifulSoup as bs
html='''<div class="legend-block legend-block--pageviews">
<h5>Pageviews</h5><hr>
<div class="legend-block--body">
<div class="linear-legend--counts">
Pageviews:
<span class="pull-right">101,172
</span>
</div>
<div class="linear-legend--counts">
Daily average:
<span class="pull-right">
4,818
</span>
</div></div></div>'''
soup = bs(html, 'html.parser')
div = soup.find("div", {"class": "linear-legend--counts"})
span = div.find('span')
text = span.get_text()
print(text)

输出:

101,172

只需在一行中:

soup = bs(html, 'html.parser')
result = soup.find("div", {"class": "linear-legend--counts"}).find('span').get_text()

编辑:

由于OP发布了另一个可能重复的问题,他找到了答案。对于正在寻找类似问题的答案的人,我将发布此问题的已接受答案。可以在这里找到它。

如果你使用 requests.get 检索页面,javascript 代码将不会执行。所以应该用硒代替。它将模仿在浏览器中打开页面时的用户行为,因此将执行js代码。

要从硒开始,您需要安装pip install selenium.然后,要检索您的项目,请使用以下代码:

from selenium import webdriver
browser = webdriver.Firefox()
# List of the page url and selector of element to retrieve.
wiki_pages = [("https://tools.wmflabs.org/pageviews/?project=en.wikipedia.org&platform=all-access&agent=user&range=latest-20&pages=Star_Wars:_The_Last_Jedi",
".summary-column--container .legend-block--pageviews .linear-legend--counts:first-child span.pull-right"),]
for wiki_page in wiki_pages:
url = wiki_page[0]
selector = wiki_page[1]
browser.get(wiki_page)
page_views_count = browser.find_element_by_css_selector(selector)
print page_views_count.text
browser.quit()

注意:如果您需要运行无头浏览器,请考虑使用 PyVirtualDisplay(Xvfb 的包装器(来运行无头 WebDriver 测试,请参阅"如何在 Xvfb 中运行 Selenium?"了解更多信息。

最新更新