【问题标题】:BeautifulSoup can not find every link in pageBeautifulSoup 找不到页面中的每个链接
【发布时间】:2021-05-21 17:15:10
【问题描述】:

这是我的代码:

from bs4 import BeautifulSoup
import requests
from requests import get
import os

def file_download():


    domain = "ec.europa.eu"
    page = requests.get("https://ec.europa.eu/eurostat/web/main/data/database")
   

    html = page.text
    soup = BeautifulSoup(html, "html.parser")

    for link in soup.find_all('a'):
        url = link.get('href')
        print(url)
        if ".gz" in url:
            file_name = url.split("file=", 1)[1]
            if os.path.exists(file_name):
                print("File already exists.")
                continue
            else:
                with open(file_name, 'wb') as file:
                    print('Downloading...')
                    response = get(url)
                    file.write(response.content)
                    continue
        else:
            continue

    print('\nEvery file has been downloaded!')

在上面的代码中,我似乎无法从页面中找到所有可能的链接。 在 chrome 检查中,复制的元素为我提供了我写的评论。 这就是我想通过 beautifulsoup 以及其他类似链接找到的内容。

【问题讨论】:

标签: python beautifulsoup python-requests-html


【解决方案1】:

最好避免通过树结构访问文件(因为这需要大量 JSON 交互)。

更简单的方法是使用他们所有文件的文件列表:

from bs4 import BeautifulSoup
import requests

session = requests.Session()
req_all = session.get("https://ec.europa.eu/eurostat/estat-navtree-portlet-prod/BulkDownloadListing?dir=data&sort=1&sort=2&start=all")
soup = BeautifulSoup(req_all.content, "lxml")
table = soup.find('table', id='filetable')

for a in table.find_all('a', href=True):
    if a.text == "Download":
        href = a['href']
    
        if '.gz' in href:
            filename = href.rsplit('%2F', 1)[1]
                
            if not os.path.exists(filename):
                with open(filename, 'wb') as f_gz:
                    f_gz.write(requests.get(href).content)
                    print(filename)

【讨论】:

    猜你喜欢
    • 2012-05-03
    • 2010-09-09
    • 2013-01-31
    • 1970-01-01
    • 2012-09-06
    • 2017-03-21
    • 1970-01-01
    • 2016-03-18
    • 1970-01-01
    相关资源
    最近更新 更多