python爬虫笔记

python笔记2020.1

编程工具 pycharm2019.3.1

关于使用pycharm进行交互调试

开启debugger提示“Process finished with exit code -1”无法进行交互式调试
**解决方法:**确保下图中的功能启动
python爬虫笔记_第1张图片

requests.get数据无法解析问题

r=requests.get(url).content
soup=BeautifulSoup(r,'html.parser')

获取的html数据必须后续转成content形式才可进行html解析(beautifulsoup解析),因为获取过来的html数据是一个Response数据类型,如下图
python爬虫笔记_第2张图片

for简写的理解

a = [x for x in range(10)]

选中for的简写代码,右键点击show contexts action,再点击Convert list comprehensions to for loop将for展开,如下图

a = []
for x in range(10):
    a.append(x)

代码a = [x for x in range(10)]等于是将for的遍历对象中的每个元素都提取出来放到a中,可以在其中加上if条件判断,将符合条件x的提取出来

a=[x for x in range(10) if x%2==0]

在这里插入图片描述
或者用在爬虫中的元素搜集

links=[i for i in soup.findAll('a') if i.has_attr('href')
       and i.has_attr('data-pan')
and i.attrs['data-pan'][0:20]=='M18_HeadNav_LeftNav_']

关于request的返回数据解码

未正常解码可能回返回的数据乱码

bytes.decode(encoding="utf-8", errors="strict")

参数encoding为当前数据的编码格式,如果网页为gbk格式编码,则使用

bytes.decode(encoding="gbk", errors="strict")

有时候解码的时候会报错,可根据情况将error参数的值设为ignore来忽略错误,继续解码,如果不知道解码参数可用response.encoding来获取当前网页的编码数据。
一般的解码方式为:

url='略'
headers={'略'}
response=requests.get(url,headers=headers)
r=response.content.decode(response.encoding,'ignore')

你可能感兴趣的:(python爬虫,python)