使用Python 3从网页提取链接时出错

时间:2017-04-20 17:26:02

标签: html regex python-3.x beautifulsoup

让我们考虑以下事项:

<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

有人可以建议在没有任何错误的情况下单独提取网址应该做些什么吗?

1 个答案:

答案 0 :(得分:1)

首先你需要循环required,其次你试图在对象regex上使用<class 'bs4.element.Tag'>(python抱怨这个),然后你需要提取{来自html元素的{1}},可以使用bs4

完成

这是一个工作版本:

prettify()

输出:

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)