xxwoaini897 发表于 2021-1-13 18:54:22

求解爬虫

import requests,json
from lxml import etree


def gethtml(url):
   
    headers={
    "User-Agent":'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
    "Cookie":"",      
    "Referer":"https://pic.sogou.com/pics?query=%E9%A2%86%E5%85%8B",
    }
    r=requests.get(url,headers=headers)   
    if r.status_code !=200:               
      print("获取url:%s失败!"%(url))
      exit()
    return r                           



def getxpath(r,str):
    html = etree.HTML(r.text)
    reslist = html.xpath(str)
    return reslist



def writetxt(txtpath,data_str):                              
    with open(txtpath, "w") as f:
      f.write(str(data_str))


def writeimg(imgpath,content):      
    with open(imgpath, "wb") as f:
      f.write(content)

def get_sogou_jpg():
    url='https://pic.sogou.com/pics?query=%E9%A2%86%E5%85%8B'
    r=gethtml(url)
    jpg_url_list=getxpath(r,'//img[@id="videoApp"]/div/div/div/ul/li/div/a/img/@src')
    jpg_url=jpg_url_list
    jpg_url="https:"+jpg_url
    r=gethtml(jpg_url)
    writeimg('./搜狗jpg.png',r.content)
    print('恭喜爬到图片')
   
if __name__ == '__main__':

    get_sogou_jpg()
    print('恭喜')

      


求解为啥超出范围,

°蓝鲤歌蓝 发表于 2021-1-13 21:22:03

报错也贴上来

xxwoaini897 发表于 2021-1-13 21:31:24

°蓝鲤歌蓝 发表于 2021-1-13 21:22
报错也贴上来

Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) on win32
Type "copyright", "credits" or "license()" for more information.
>>>
======================== RESTART: D:/桌面图标文件目录/妹子图.py ========================
Traceback (most recent call last):
File "D:/桌面图标文件目录/妹子图.py", line 48, in <module>
    get_mezitu()
File "D:/桌面图标文件目录/妹子图.py", line 40, in get_mezitu
    mezitu_url=mezitu_url_list
IndexError: list index out of range
>>>

°蓝鲤歌蓝 发表于 2021-1-13 21:35:59

xxwoaini897 发表于 2021-1-13 21:31
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) on win32
Type ...

这个错误这么明显
jpg_url_list=getxpath(r,'//img[@id="videoApp"]/div/div/div/ul/li/div/a/img/@src')
上面那行代码匹配出来的列表为空列表,原因如下:
1. 可能是 r 没有内容
2. r 有内容,但是 内容 里没有你要匹配的字符串
3. 匹配规则有误
不过我建议你先学习怎么看报错和调试。

xxwoaini897 发表于 2021-1-15 11:21:41

°蓝鲤歌蓝 发表于 2021-1-13 21:35
这个错误这么明显

上面那行代码匹配出来的列表为空列表,原因如下:


非常感谢您,都是断断续续自学了一点,哪里可以看到最新的爬虫教程?就想学会爬虫。

°蓝鲤歌蓝 发表于 2021-1-15 16:02:35

xxwoaini897 发表于 2021-1-15 11:21
非常感谢您,都是断断续续自学了一点,哪里可以看到最新的爬虫教程?就想学会爬虫。

B站找个日期近的,播放人数较多,评论里说还可以,自己看着也还行的视频就 OK 了。
页: [1]
查看完整版本: 求解爬虫