Python模拟谷歌浏览器获取网页内容,反反爬虫

今天爬取网页内容和文件遇到了 反爬虫,找到了一个比较好的示例代码

import urllib.request

# 要获取数据的 URL
url = "https://www.example.com/"

# 谷歌浏览器的 User-Agent 字符串
user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"

# 创建一个带有 User-Agent 头的请求
req = urllib.request.Request(url, headers={"User-Agent": user_agent})

# 读取网页数据
response = urllib.request.urlopen(req)

# 解码数据并将其转换为字符串
html = response.read().decode('utf-8')

# 打印获取的数据
print(html)

猜你喜欢

转载自blog.csdn.net/jackwu11/article/details/129152777
今日推荐