python爬虫Python数据采集与爬虫python爬虫

记第一次爬虫

2016-06-10  本文已影响242人  宇文黎琴

爬上海证券网的大标题和top-topic。使用的是beautifulsoup。

过程中遇到的问题

网页结构不难,我希望能得到网页中所有的大标题--》就是<h1/>标签中的标题和top-toptic中所有的标题。

1.beautifulsoup中findAll函数不支持交集的查找。

findAll函数中的参数只支持并集的查找,比如:

 print(bsObj.findAll("div","h1","a"))

会把所有div,h1,a标签的内容全部提取出来,而不是div中h1,h1中a的标签的内容。如果需要这样查找,也可以用children函数来实现。但是用位置定位你需要的内容太麻烦了。
所以我的解决办法是,分别查找然后去重。然后就遇到第二个问题

2.如何对中文进行比较

在beautifulsoup里中文编码是Unicode。但是python中比较字符串是否一致的函数。在上证网中top-list含在一个class属性值为top-area 的div里面,当我对这个div进行提取文字,是提取了这个段落里面的所有的文字。这些文字是被当做连续的内容整体处理的。也就是说里面的文字的内容可能是来自<h1/>标题,也可能是来自<h2/>标题等。所以可以用找子串的函数来处理。如果查找<h1/>标题在<div/>标签里面出现,就删除。

index = Obj_toplist.get_text().find(obj_h1.get_text())

删除函数是

Objs_h1.remove(remove_list)
3.去除重复的标签

对于list可以用remove去除list中第一个匹配成功的元素。但是remove会让list的长度减1.所以如果有俩个连续的位置需要去除。不能识别一个去除一个。这样会漏掉俩个连续位置的中的第二个元素。做法是对于遇到的重复的标签,先储存,然后一次性全部去除。

for remove_list in removes_list:
             Objs_h1.remove(remove_list)

以下是源代码

from urllib.request import urlopen
from bs4 import BeautifulSoup
import re


html  = urlopen("http://www.cnstock.com")
bsObj = BeautifulSoup(html,"html.parser")

Objs_h1      = bsObj.findAll("h1")
Objs_toplist = bsObj.findAll("div",{"class":"top-area"})
removes_list = []

#去除重复的文字【重要新闻处理】
for Obj_toplist in Objs_toplist:
    for obj_h1 in Objs_h1:
    index = Obj_toplist.get_text().find(obj_h1.get_text())
    if index !=-1 :
        removes_list.append(obj_h1)

for remove_list in removes_list:
Objs_h1.remove(remove_list)


print("重要新闻")
for Obj_h1 in Objs_h1:
    print(Obj_h1.get_text())
for Obj_toplist in Objs_toplist:
    print(Obj_toplist.get_text())
上一篇下一篇

猜你喜欢

热点阅读