繁体   English   中英

美丽的汤找到 function 从谷歌刮掉号码

[英]beautiful soup find function to scrape number off google

我刚刚看完了一个关于美汤的教程,我想我会用它来尝试从谷歌上抓取一些数据。

我刚刚用谷歌搜索了英国冠状病毒,并想获取当前确诊病例数。

web 页面的右上角是一个框,显示了英国的确诊病例数。 在检查元素后,我发现它位于此块中:

<td jsname="VBiLTe" class="dZdtsb QmWbpe ZDeom" data-absolute-value="276332" data-is-data-cell="true" 
data-per-million-value="4258.258906030955" data-vfs="276332"><div class="amyZLb">Confirmed</div><div 
class="m7B03"><div jsname="fUyIqc"><span>276K</span></div><div jsname="KBqmYc" style="display:none">
<span>4,258</span></div></div><div class="h5Hgwe"><div jsname="fUyIqc">+<span>1,570</span></div></div>
</td>

上述代码块中的 data-vfs 键包含我要抓取的值。 我认为这段代码可以用来刮取价值。

from bs4 import BeautifulSoup
import requests

source = requests.get("https://www.google.com/search?q=coronavrius+uk&rlz=1C1CHBF_en-GBGB813GB813&oq=cor&aqs=chrome.0.69i59l2j0j69i57j35i39j69i64j69i60l2.1384j0j4&sourceid=chrome&ie=UTF-8").text
soup = BeautifulSoup(source,'lxml')

test=soup.find("td",class_="dZdtsb QmWbpe ZDeom")
print(test["data-vfs"])

但是,测试返回为无,(在运行代码时出现错误)暗示什么也没找到? 我一直试图弄清楚为什么多年来,但没有想到。 如何修改find中的arguments来刮号?

要从 Google 提供的页面获取信息,您需要指定User-Agent header。

例如:

import requests
from bs4 import BeautifulSoup


url ='https://www.google.com/search?hl=en&q=corona+virus+uk'
headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:76.0) Gecko/20100101 Firefox/76.0'}

soup = BeautifulSoup( requests.get(url, headers=headers).content, 'html.parser' )

table1 = soup.select_one('div:has(span:contains("United Kingdom")) + table')
table2 = soup.select_one('div:has(span:contains("Worldwide")) + table')

print('UK:')
print('-'*80)
for td in table1.select('td'):
    print(td.get_text(strip=True, separator=' '))

print()

print('World:')
print('-'*80)
for td in table2.select('td'):
    print(td.get_text(strip=True, separator=' '))

印刷:

UK:
--------------------------------------------------------------------------------
Confirmed 276K 4,258 + 1,570
Recovered -
Deaths 39,045 602 + 0

World:
--------------------------------------------------------------------------------
Confirmed 6.06M 860 + 123K
Recovered -
Deaths 371K 53 + 4,000

编辑:截至 2020 年 7 月 6 日运行代码打印:

UK:
--------------------------------------------------------------------------------
Confirmed 285K 4,398 + 624
Recovered -
Deaths 44,220 681 + 67

World:
--------------------------------------------------------------------------------
Confirmed 11.4M 1,621 + 203K
Recovered 6.16M 874
Deaths 534K 76 + 5,193

有可能“jsname”表示web页面的这个块是在主页加载后被javascript动态加载的。 BeautifulSoup 因为您正在使用它将下载源代码,但在解析之前不会在页面上执行任何 javascript。

您可能想查看“Selenium”,这是一个无头浏览器,或者使用来自更简单来源的 static 页面学习 BeautifulSoup。 例如,谷歌从某个地方获取数据,找到源并抓取该页面。

祝你好运!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM