2016-07-31 74 views
1

我想在下面的网站中使用美丽的汤在python 3.5中提取信息。美丽的汤只是提取一张桌子的标题

http://www.askapatient.com/viewrating.asp?drug=19839&name=ZOLOFT 

我必须先保存网页,因为我的程序需要脱机工作。

我将网页保存在我的电脑中,并使用以下代码来提取表格信息。但问题是代码只是提取表格的标题。

这是我的代码:

from urllib.request import Request, urlopen 
from bs4 import BeautifulSoup 
url = "file:///Users/MD/Desktop/ZoloftPage01.html" 


home_page= urlopen(url) 
soup = BeautifulSoup(home_page, "html.parser") 
table = soup.find("table", attrs={"class":"ratingsTable" }) 
comments = [td.get_text() for td in table.findAll("td")] 
print(comments) 

这是代码的输出:

['RATING', '\xa0 REASON', 'SIDE EFFECTS FOR ZOLOFT', 'COMMENTS', 'SEX', 'AGE', 'DURATION/DOSAGE', 'DATE ADDED ', '\xa0’] 

我需要在表中的所有行的信息。 感谢您的帮助!

回答

1

这是因为页面的损坏的HTML。您需要切换到更多宽松解析器,比如html5lib。这里是适合我的东西:

from pprint import pprint 

import requests 
from bs4 import BeautifulSoup 

url = "http://www.askapatient.com/viewrating.asp?drug=19839&name=ZOLOFT" 
response = requests.get(url, headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36'}) 

# HTML parsing part 
soup = BeautifulSoup(response.content, "html5lib") 
table = soup.find("table", attrs={"class":"ratingsTable"}) 
comments = [[td.get_text() for td in row.find_all("td")] 
      for row in table.find_all("tr")] 
pprint(comments) 
+0

非常感谢你!我正在使用python 3.5。代码有以下错误:“ImportError:无法导入名称'请求'” – Mary

+0

@在此下载页面源部分其实并不相关。但是,如果您想按照原样使用示例,则需要安装['requests'模块](http://docs.python-requests.org/en/master/)。 – alecxe

+0

我非常感谢。非常感谢 ! – Mary