【问题标题】:Beautiful soup just extract header of a table美丽的汤只是提取表头
【发布时间】:2016-07-31 01:51:59
【问题描述】:

我想在 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’]

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

【问题讨论】:

    标签: python python-3.x beautifulsoup bs4


    【解决方案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)
    

    【讨论】:

    • 非常感谢!我正在使用 python 3.5。代码有以下错误:“ImportError: cannot import name 'requests'”
    • @Mary 下载页面源代码部分其实和这里无关。但是,如果您想按原样使用该示例,则需要安装 requests module
    • 我非常感谢。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-19
    • 2021-04-03
    • 2016-09-11
    • 2015-05-08
    • 2018-09-13
    • 2021-05-24
    • 2015-10-21
    相关资源
    最近更新 更多