
怎么用python检查网页
用户关注问题
我想用Python查看某个网页的HTML源代码,应该使用哪些库或方法?
使用requests库获取网页HTML
你可以使用Python的requests库发送HTTP请求来获取网页的HTML内容。示例代码如下:
import requests
url = 'http://example.com'
response = requests.get(url)
html_content = response.text
print(html_content)
这段代码将会打印出网页的HTML源码。
拿到网页HTML后,我想提取标题或者链接等信息,有什么推荐的Python库吗?
使用BeautifulSoup解析网页HTML
BeautifulSoup是一个用于解析HTML和XML文档的Python库。结合requests库使用,可以方便地提取网页中特定标签或数据。例如:
from bs4 import BeautifulSoup
import requests
url = 'http://example.com'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
titles = soup.find_all('h1')
for title in titles:
print(title.text)
该方法可以帮助你快速提取网页中的文本内容。
在使用Python检查网页时,想判断网页是否正常打开以及响应速度,应怎么办?
利用requests库查看状态码和响应时间
requests库返回的Response对象包含状态码和响应时间信息。通过response.status_code可以判断网页是否正常访问,response.elapsed.total_seconds()可以查看响应耗时。例如:
import requests
url = 'http://example.com'
response = requests.get(url)
print('状态码:', response.status_code)
print('响应时间:', response.elapsed.total_seconds(), '秒')
状态码为200意味着网页正常响应。