【问题标题】:BeautifulSoup with dynamic href带有动态href的BeautifulSoup
【发布时间】:2016-07-09 21:08:18
【问题描述】:

尝试使用 python 3.4 beautifulsoup 从网页中获取 zip 文件,以便我可以解压缩并将其下载到文件夹中。我可以让 beautifulsoup 打印()页面上的所有 href,但我想要一个特定的 href 结尾,“=Hospital_Revised_Flatfiles.zip”。那可能吗?这是我目前所拥有的,只有来自 url 的 href 列表。

文件的完整href是https://data.medicare.gov/views/bg9k-emty/files/Dlx5-ywq01dGnGrU09o_Cole23nv5qWeoYaL-OzSLSU?content_type=application%2Fzip%3B%20charset%3Dbinary&filename=Hospital_Revised_Flatfiles.zip ,但是当他们更新文件时,中间的疯狂的东西会发生变化,并且无法知道它会变成什么。

如果我在问题中遗漏了一些可能有帮助的内容,请告诉我。我正在使用 Python 3.4 和 BeautifulSoup4 (bs4)

from bs4 import BeautifulSoup 
import requests
import re

url = "https://data.medicare.gov/data/hospital-compare"

r = requests.get(url)

data = r.text

soup = BeautifulSoup(data)

for link in soup.find_all('a'):
    print(link.get('href'))

【问题讨论】:

    标签: python-3.x beautifulsoup href


    【解决方案1】:
    from BeautifulSoup import BeautifulSoup 
    import requests
    import re
    
    url = "https://data.medicare.gov/data/hospital-compare"
    
    r = requests.get(url)
    
    data = r.text
    
    soup = BeautifulSoup(data)
    
    for link in soup.findAll('a'):
       if link.has_key('href'):
          if(link['href'].endswith("=Hospital_Revised_Flatfiles.zip")):
             print(link['href'])
    

    【讨论】:

    • 当我使用该代码时,我收到“无效语法”错误
    • 试试这个我已经修改并检查了代码,它现在可以工作了。
    • 我认为这已经接近我所需要的了。唯一的问题是它没有给出整个链接,只是以“hospital_revised_flatfiles.zip”结尾的href。也许我错过了什么。
    • 我只更改了代码中的两处以使其正常工作。 1) 将 has_key 更改为 has_attr 2) print('data.medicare.gov'+link['href']. 感谢@WhoAmI 的帮助
    猜你喜欢
    • 2010-12-25
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    • 2012-10-25
    • 2022-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多