Python爬虫,求解决

为什么结果不是网址源代码。skkdbjdosksjdjdkdls。

img

因为 百度识别了,你这个是爬虫程序,所以给你的而是假数据, 在请求的时候 添加请求头,添加 user-agent 就可以了
学习爬虫直接使用 requests 吧 更好用

添加一个请求头就行了。

from urllib import request


url = 'https://www.baidu.com/'
headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3877.400 QQBrowser/10.8.4507.400'
}

req = request.Request(url=url,headers=headers)
rsp = request.urlopen(req)
print(rsp.read().decode('utf-8'))

不懂的可以去看看我的爬虫专栏啊!
https://blog.csdn.net/qq_45404396/category_9687415.html
还有建议使用requests模块,这个模块实现同样的效果的代码量相较而言会少些。

可以使用 requests 库

import requests

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.82 Safari/537.36'
}

url = 'https://www.baidu.com'

rep = requests.get(url)
print(rep.text)