我正在尝试编写一个收集当前在本站上列出的数据集数量的剪贴器。
看看我的密码。
from requests import exceptions
import requests
from bs4 import BeautifulSoup
site='https://data.gov/index.html/'
try:
html_content=requests.get(site).text
except exceptions.RequestException as e:
print('there is a problem with reaching this site')
soup=BeautifulSoup(html_content, 'lxml')
needed_text=soup.find('label',{'for':'search-header'})
for text in needed_text:
try:
final_text=text.find('a').attrs['href']
print('there are {} data sets currently listed on data.gov'.format(final_text.get_text()))
except:
continue但是,当我运行这段代码时,它不会得到任何结果。
我打印了网站的HTML脚本,找不到我需要的特定数据。我可以在浏览器上看到它,但在我的IDE中找不到它。
请帮帮忙。
发布于 2022-04-23 10:25:59
url错误并返回404。你自己看吧。
另外,将代码的soup部分移到try except块可能是个好主意。最后,不需要使用for loop,因为只有一个元素包含您想要的数据。
试试这个:
import requests
from requests import exceptions
from bs4 import BeautifulSoup
site = 'https://data.gov'
try:
html_content = requests.get(site).text
soup = BeautifulSoup(html_content, 'lxml')
needed_text = soup.select_one("small > a[href]").getText()
print(needed_text)
except exceptions.RequestException as e:
print('there is a problem with reaching this site')输出:
335,221 datasetshttps://stackoverflow.com/questions/71967985
复制相似问题