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沒有任何錯誤?