【问题标题】:Use beautifulsoup to download href links使用beautifulsoup下载href链接
【发布时间】:2021-10-27 01:21:33
【问题描述】:

希望使用 beautifulsoup4、python 3 和 requests 库下载 href 链接。

这是我现在拥有的代码,我认为在这种情况下使用正则表达式会很困难,但我不确定是否可以使用 beautifulsoup3 来完成。我必须从网格中下载所有形状文件,并希望自动执行此任务。谢谢!

网址: https://earth-info.nga.mil/index.php?dir=coordsys&action=gars-20x20-dloads

import requests
from bs4 import BeautifulSoup
import re


URL = 'https://earth-info.nga.mil/index.php?dir=coordsys&action=gars-20x20-dloads'

page =  requests.get(URL)

soup = BeautifulSoup(page.content,'html.parser')




results = re.findall(r'<a[^>]* href="([^"]*)"', page)

print(results)

【问题讨论】:

    标签: python-3.x web-scraping beautifulsoup python-requests


    【解决方案1】:

    这些文件都与area标签相关联,所以我会简单地选择那些:

    import requests
    from bs4 import BeautifulSoup as bs
    
    r = requests.get('https://earth-info.nga.mil/index.php?dir=coordsys&action=gars-20x20-dloads')
    soup = bs(r.content, 'lxml')
    files = ['https://earth-info.nga.mil/' + i['href'] for i in soup.select('area')]
    

    【讨论】:

    • 您应该在https://earth-info.nga.mil 之后使用正斜杠 (/),否则填充的链接将无效。
    • 啊...谢谢@SIM
    【解决方案2】:

    您可以将page 转换为字符串,以便使用正则表达式搜索所有a

    代替:

    results = re.findall(r'<a[^>]* href="([^"]*)"', page)
    

    用途:

    results = re.findall(r'<a[^>]* href="([^"]*)"', page.text)
    

    【讨论】:

      猜你喜欢
      • 2019-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-10
      • 2019-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多