2017-04-20 6 views
1

を使用してWebページからリンクを抽出しながら、:エラー私たちは次のことを考えるの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

これを達成するために、PythonでBeautifulSoupと正規表現を使用してコードを書きました。次のようにコードは次のとおりです。実行に

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

まずあなたが二あなたは(Pythonはこの不満た)オブジェクト<class 'bs4.element.Tag'>regexを使用しようとしている、あなたはprettify()で行うことができますbs4要素からhtmlを抽出する必要があり、ループrequiredに必要

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 
...