py网络爬虫

tech2022-08-29  127

最近在看崇天老师的MOOC Python网络爬虫与信息提取课程,先开个头 首先必须安装requests 库 方法很简单 pip install requests即可 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-aW55ejx9-1599285480514)(/img/bVbMkeh)] 以上是requests 库中的7个主要方法

import requests url='http://www.baidu.com' r=requests.get(url) print(r.status_code) r.encoding='utf-8' print(r.text)

简单抓取百度的代码

r=requests.get(url) 在这行代码中,返回r的数据类型是Response类,赋值号右边的是Request类

Response对象属性(重要)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cwG13p6e-1599285480517)(/img/bVbMkfA)]

Requests库的异常

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yTu9bPnR-1599285480518)(/img/bVbMkgu)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-sUEEt355-1599285480519)(/img/bVbMkgI)]

params的用法

一、爬取京东实例

1.在爬取京东网站的时候

import requests url='https://item.jd.com/100006713417.html' try: r=requests.get(url) print(r.status_code) print(r.text[:1000]) except : print('出现异常')

得到这个结果: 显然这不是我们想要的信息,访问结果中的链接发现是京东的登录界面。

2.解决问题 在查找了相关资料之后,发现京东是有来源审查的,于是可以通过修改headers和cookie参数来实现 cookie参数查找方法: 进入页面之后按F12,然后进入network界面,刷新之后找到对应的页面,如图

import requests url = 'https://item.jd.com/100006713417.html' cookiestr='unpl=V2_ZzNtbRAHQ0ZzDk9WKBlbDWJXQF5KBBYRfQ0VBHhJWlEyABBaclRCFnQUR11nGlUUZwYZWEdcRxxFCEVkexhdBGAAE19BVXMlRQtGZHopXAFvChZVRFZLHHwJRVRyEVQDZwQRWENncxJ1AXZkMEAaDGAGEVxHVUARRQtDU34dXjVmMxBcQ1REHXAPQ11LUjIEKgMWVUtTSxN0AE9dehpcDG8LFF1FVEYURQhHVXoYXAJkABJtQQ%3d%3d; __jdv=122270672|mydisplay.ctfile.com|t_1000620323_|tuiguang|ca1b7783b1694ec29bd594ba2a7ed236|1598597100230; __jdu=15985970988021899716240; shshshfpa=7645286e-aab6-ce64-5f78-039ee4cc7f1e-1598597100; areaId=22; ipLoc-djd=22-1930-49324-0; PCSYCityID=CN_510000_510100_510116; shshshfpb=uxViv6Hw0rcSrj5Z4lZjH4g%3D%3D; __jdc=122270672; __jda=122270672.15985970988021899716240.1598597098.1598597100.1599100842.2; shshshfp=f215b3dcb63dedf2e335349645cbb45e; 3AB9D23F7A4B3C9B=4BFMWHJNBVGI6RF55ML2PWUQHGQ2KQMS4KJIAGEJOOL3ESSN35PFEIXQFE352263KVFC2JIKWUJHDRXXMXGAAANAPA; shshshsID=2f3061bf1cc51a3f6162742028f11a80_5_1599101419724; __jdb=122270672.11.15985970988021899716240|2.1599100842; wlfstk_smdl=mwti16fwg6li5o184teuay0iftfocdez' headers = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.14 Safari/537.36 Edg/83.0.478.13","cookie":cookiestr} try: r = requests.get(url=url,headers=headers) r.raise_for_status() r.encoding = r.apparent_encoding print(r.text[:1000]) except: print('爬取失败') import requests kv = {'user-agent':'Mozilla/5.0'} url = "https://item.jd.com/100006713417.html" try: r = requests.get(url,headers = kv) r.encoding = r.apparent_encoding r.raise_for_status() print(r.text[:1000]) except : print('Error')

均得到了我们想要的结果

二、爬取亚马逊实例

import requests url = "https://www.amazon.cn/dp/B072C3KZ48/ref=sr_1_5?keywords=Elizabeth+Arden+%E4%BC%8A%E4%B8%BD%E8%8E%8E%E7%99%BD%E9%9B%85%E9%A1%BF&qid=1599103843&sr=8-5" try: r = requests.get(url) print(r.status_code) print(r.encoding) print(r.request.headers) r.encoding = r.apparent_encoding print(r.text[:5000]) except : print('Error')

同样的问题出现了,老师在这里做了讲解,亚马逊也是有来源审查的,在没有修改headers参数的时候,程序告诉亚马逊服务器这是个py requests库的访问 所以出现了错误。 2.解决方法 和上面一样,修改user-agent即可 结果: 还是出现了问题,下方有提示, 这里提示可能出现了与cookie相关的问题,于是我们找到网页的cookie,放到headers里面去 问题成功解决

三、爬取图片

当我们想要爬取网页上面的图片的时候我们应该怎么做呢。 现在知道网页上的图片链接的格式为 url链接以jpg结尾说明为图片

根据崇天老师的提示写了一段代码

import requests import os url='https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2588111137,2818876915&fm=26&gp=0.jpg' root='d:/pics//' path = root+url.split('/')[-1] try: if not os.path.exists(root): os.makedirs(root) if not os.path.exists(path): r=requests.get(url) with open(path,'wb') as f: f.write(r.content) f.close() print('文件保存成功') else: print('文件已经存在') except: print('爬取出错')

这里import os来判断文件时候存在 上结果 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xv0bBm8f-1599285480521)(/img/bVbMr7U)] [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7tOVoMvj-1599285480521)(/img/bVbMr7W)] 图片也得到了保存

IP地址归属地自动查询

在进行实战的过程中遇到了小问题 先上代码

import requests url_1 = 'https://www.ip138.com/iplookup.asp?ip=112.44.101.245&action=2' ip_address = input('Please input your ip address') url = url_1+ip_address+'&action=2' if ip_address: try: r = requests.get(url) print(r.status_code) print(r.text[-500:]) except: print('error') else: print('ip address cannot be empty')

然后程序一直报error,于是我拿掉了try except模块,看看问题出在哪 果然问题出在来源审查 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FF8AqVZd-1599285480522)(/img/bVbMr9Y)]

这行报错说明了ip138网站应该是有来源审查,于是改掉headers中的agent再试试 修改user-agent参数之后,随便找了个美国的IP地址,成功了先上图 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-puo6nDNG-1599285480522)(/img/bVbMsaQ)]

import requests url_1 = 'https://www.ip138.com/iplookup.asp?ip=' ip_address = input('Please input your ip address') kv={'user-agent':'chrome/5.0'} url = url_1+ip_address+'&action=2' if ip_address: try: r = requests.get(url,headers=kv) print(r.status_code) r.encoding=r.apparent_encoding print(r.text) except: print('error') else: print('ip address cannot be empty')

第二周

Beautiful Soup库

1.安装Beautiful Soup库

CMD pip install beautifulsoup4

2.requests库获取网页源代码

import requests r=requests.get("https://python123.io/ws/demo.html") print(r.text)

3. bs库的使用

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tKeVDKKg-1599285480523)(/img/bVbMsca)]

import requests from bs4 import BeautifulSoup r = requests.get("https://python123.io/ws/demo.html") demo = r.text soup = BeautifulSoup(demo,'html.parser') print(soup.prettify())

4. bs库的基本元素

最新回复(0)