爬虫正则表达式到不到目标
想随便爬取百度的图练练手,但是用正则表达式找不到对应的标签.....是我用错了吗,求大佬指教import re
import urllib.request
def open_url(url):
req = urllib.request.Request(url)
req.add_header('User-Agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36')
response = urllib.request.urlopen(req)
html = response.read().decode('utf-8')
return html
url = "https://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=index&fr=&hs=0&xthttps=111111&sf=1&fmq=&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=%E5%93%88%E5%88%A9%E6%B3%A2%E7%89%B9&oq=%E5%93%88%E5%88%A9&rsp=0"
html = open_url(url)
p = r'<img class="main_img img-hover" data-imgurl=[^"]+\.jpg'
print(re.findall(p,html))
t = re.findall(p,html)
for i in t:
print(i)
本帖最后由 Twilight6 于 2020-6-27 22:54 编辑
看了下 爬取出来的网站源码里面本来就没有包含这些节点 就算你写的是正确的你也肯定匹配不到了
还有实际上 url 很多都可以不要的,比如你可以访问这个,比你的短了2倍 也是你访问那个网站的结果:
https://image.baidu.com/search/index?tn=baiduimage&word=%E5%93%88%E5%88%A9%E6%B3%A2%E7%89%B9&oq=%E5%93%88%E5%88%A9&rsp=0
“检查”功能不准
【查看原码】才是真的原码 看了下,百度的这个图片搜索结果是通过ajax加载的:
所以直接get搜索结果首页是拿不到的,不过ajax的参数在get搜索结果首页时给出了,那么模拟ajax请求就行了。
对比几次翻页(滚轮)产生的ajax请求,发现只有3个参数在变,所以构建ajax请求时就主要修改这几个参数。
页:
[1]