天天看點

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入門級爬取百度百科詞條

學習連結

崔慶才的個人部落格