天天看点

Python入门级爬取百度百科词条

爬取 Angelababy词条历史版本 中的value值。

尝试爬取网页

# _*_ coding:utf-8 _*_
import urllib
import urllib2
import re
page = 1
url = 'https://baike.baidu.com/historylist/Angelababy/1509275#page'+str(page)
try:
    request = urllib2.Request(url)
    response = urllib2.urlopen(request)
    print response.read()
except urllib2.URLError, e:
    if hasattr(e,"code"):
        print e.code
    if hasattr(e,"reason"):
        print e.reason      

运行结果:

Python入门级爬取百度百科词条

可以看到已经爬取了此网页所有的内容。现在需要实现的就是爬取想要的value值了。

爬取目标内容

Python入门级爬取百度百科词条

可以看到要爬取的内容,格式全部一样都是图中所示,代码如下:

<tr>
    <td class="checkBox">
        <input type="checkbox" value="128140635">
    </td>
      .
      .
      .
</tr>      

所以我们做以下正则匹配:

pattern = re.compile('<tr>.*?<td class="checkBox">.*?<input.*?value="(.*?)">.*?</td>.*?</tr>',re.S)      

全部代码如下:

# _*_ coding:utf-8 _*_
import urllib
import urllib2
import re
page = 1
url = 'https://baike.baidu.com/historylist/Angelababy/1509275#page'+str(page)
try:
    request = urllib2.Request(url)
    response = urllib2.urlopen(request)
    content = response.read().decode('utf-8')
    pattern = re.compile('<tr>.*?<td class="checkBox">.*?<input.*?value="(.*?)">.*?</td>.*?</tr>',re.S)
    items = re.findall(pattern,content)
    for item in items:
        print(item)
except urllib2.URLError,e:
    if hasattr(e,"code"):
        print e.code
    if hasattr(e,"reason"):
        print e.reason      

爬取结果如下:

Python入门级爬取百度百科词条

学习链接

崔庆才的个人博客