如何使用BeautifulSoup检查网站标题更改?

2024-04-25 05:21:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试检查此网站的标题更改: https://allestoringen.nl/storing/kpn/

source = requests.get(url).text
soup = bs4.BeautifulSoup(source,'html.parser')
event_string = str(soup.find(text='Er is geen storing bij KPN'))

print (event_string)

但是,event_string每次返回None


Tags: texthttpseventurl标题sourcegetstring
1条回答
网友
1楼 · 发布于 2024-04-25 05:21:11

你没有得到结果的原因可能是网站不接受你的请求。我得到了这个结果

page = requests.get(url)

page.status_code  # 403
page.reason       # 'Forbidden'

您可能需要查看thispost以获得解决方案

最好在代码中检查请求的返回状态

但要解决你的问题。您可能希望检查<title>元素,而不是特定的字符串

# stolen from the post I mentioned
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}

page = requests.get(url, headers=headers)
page.status_code  # 200. Adding a header solved the problem.
soup = bs4.BeautifulSoup(page.text,'html.parser')

# get title.
print(soup.find("title").text)
'KPN storing? Actuele storingen en problemen | Allestoringen'

相关问题 更多 >