2017-04-20 120 views
1
從網頁中提取鏈接

讓我們考慮以下幾點:錯誤而使用Python 3

<div class="more reviewdata"> 

<a onclick="bindreviewcontent('1660651',this,false,'I found this review of Star Health Insurance pretty useful',925075287,'.jpg','I found this review of Star Health Insurance pretty useful %23WriteShareWin','http://www.mouthshut.com/review/Star-Health-Insurance-review-toqnmqrlrrm','Star Health Insurance',' 2/5');" style="cursor:pointer">Read More</a> 

</div> 

從類似上述情況,我想單獨提取http鏈接如下:

http://www.mouthshut.com/review/Star-Health-Insurance-review-toqnmqrlrrm

爲了達到這個目的,我使用BeautifulSoup和Python中的正則表達式編寫了一個代碼。代碼如下:

import urllib.request 
import re 

from bs4 import BeautifulSoup 
page = urllib.request.urlopen('http://www.mouthshut.com/product-reviews/Star-Health-Insurance-reviews-925075287').read() 

soup = BeautifulSoup(page, "html.parser") 

required = soup.find_all("div", {"class": "more reviewdata"}) 

for link in re.findall('http://www.mouthshut.com/review/Star-Health-Insurance-review-[a-z]*', required): 
    print(link) 

在執行時,如下程序拋出一個錯誤:

Traceback (most recent call last): 

File "E:/beautifulSoup20April2.py", line 11, in <module> 

for link in re.findall('http://www.mouthshut.com/review/Star-Health-Insurance-review-[a-z]*', required): 

File "C:\Program Files (x86)\Python35-32\lib\re.py", line 213, in findall 
return _compile(pattern, flags).findall(string) 

TypeError: expected string or bytes-like object 

有人建議應該做什麼單獨提取URL沒有任何錯誤?

回答

1

首先,你需要循環required,第二你要的對象<class 'bs4.element.Tag'>上使用regex(蟒蛇在抱怨這一點),那麼你就需要從bs4元素,它可以與prettify()進行提取html

這裏有一個工作版本:

import urllib.request 
import re 
from bs4 import BeautifulSoup 
page = urllib.request.urlopen('http://www.mouthshut.com/product-reviews/Star-Health-Insurance-reviews-925075287').read() 
soup = BeautifulSoup(page, "html.parser") 
required = soup.find_all("div", {"class": "more reviewdata"}) 
for div in required: 
    for link in re.findall(r'http://www\.mouthshut\.com/review/Star-Health-Insurance-review-[a-z]*', div.prettify()): 
     print(link) 

輸出:

http://www.mouthshut.com/review/Star-Health-Insurance-review-ommmnmpmqtm 
http://www.mouthshut.com/review/Star-Health-Insurance-review-rmqulrolqtm 
http://www.mouthshut.com/review/Star-Health-Insurance-review-ooqrupoootm 
http://www.mouthshut.com/review/Star-Health-Insurance-review-rlrnnuslotm 
http://www.mouthshut.com/review/Star-Health-Insurance-review-umqsquttntm 
...