爬虫遇到的问题

我在爬取网页过程遇到的问题:
对象可以归纳为4种: Tag , NavigableString , BeautifulSoup , Comment .
tag.name获取的是标签名,比如

duie

返回的是p

soup = bs('<div id="sinaTail" style="position: absolute;">jdiejdiediv>','lxml')
>>> b = soup.div
>>> b.name
'div'

1)*tag的 .contents 属性可以将tag的子节点以列表*的方式输出:
这如下是爬取内容时出现的问题,我们获取class= ‘p1’随后的东西
爬虫遇到的问题_第1张图片

soup = bs(html,'lxml')
>>> soup.find('div','p1').contents[0]
'发布时间:2017年08月01日 15:46 来源:中新网湖北'

我们就获取到了我们的内容,此时不能使用findall方法,有的可能还分不清各个方法的区别,返回的错误提示:

soup.find_all('div','p1').contents[0]
Traceback (most recent call last):
  File "", line 1, in <module>
    soup.find_all('div','p1').contents[0]
AttributeError: 'ResultSet' object has no attribute 'contents'

2)还有在爬取网页新闻正文内容的过程中,会经常碰到如下代码:
新闻内容大多都在P标签内部,在找到文本内容的div标签后,要找到所有的文本,就会使用到以下方法:


[each.text for each in soup.find('div', attrs={'id': "content_text"}).find_all('p')]

这里会对find方法进行说明:

find( name , attrs , recursive , text , **kwargs )
name指的是标签的名字,attrs就是各种属性,当是class是可以省略不写(class = 'ss'),但是为其他情况是要给予说明,通常有两种,当id = ‘share’是
soup.find('div','ss')#不用写class
第一种方法:soup.find('div',id = 'share')#要写id
第二种方法;soup.find('div',attrs = {'id':'share'})
这种就是使用find_all()方法的attrs 参数定义一个字典参数来搜索包含特殊属性的tag:

还有最多的就是编码问题了:
解决方法1:soup.find(res.content,'lxml',from_encoding = 'gbk')
解决方法2:在requests URL前编码:
r = requests.get(url)
r.encoding = 'utf-8'
#根据自己的需要设置把
在需要的时候encode和decode把

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