【问题标题】:Errno 11001 getaddrinfo failed when looping over urlsErrno 11001 getaddrinfo 在遍历 url 时失败
【发布时间】:2019-08-20 16:25:40
【问题描述】:

我想从某些页面中提取文档列表。

当我尝试循环访问 url 列表时遇到问题

Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))

感谢澄清为什么会这样。

如果我运行一个 url 页面,但应该没有问题。

我有一个使用 Selenium/Webdriver 的单独代码,但是使用 Selenium 的问题是不同文件类型的下载行为。

例如,如果一个 url 将您带到一个 pdf 文件,它将打开一个显示完整 pdf 文件的新页面。如果 url 链接到 Excel 文件,则行为会有所不同。

更多细节可以在这里找到How do I control Selenium PDF and Excel files download behavior?

我最终得到了下面的建议代码,虽然它可能不使用 Selenium,但它完成了获取所有文件的工作。

谢谢!

import requests
from bs4 import BeautifulSoup
import re
import pandas as pd
import os

doc_urls = ['http://www.ha.org.hk/haho/ho/bssd/18G042Pc.htm'
'http://www.ha.org.hk/haho/ho/bssd/HKWCT03018A2Pa.htm',
'http://www.ha.org.hk/haho/ho/bssd/19D070Pa.htm',
'http://www.ha.org.hk/haho/ho/bssd/NTECT6AQ011Pa.htm',
'http://www.ha.org.hk/haho/ho/bssd/T18G052Pa.htm',
]

base_url = "http://www.ha.org.hk"


for doc in doc_urls:
    with requests.Session() as session:
        r = session.get(doc)
        # get all documents links
        docs = BeautifulSoup(r.text, "html.parser").select("a[href]")
        print('Visiting:',doc)
        for doc in docs:
            href = doc.attrs["href"]
            name = doc.text
            print(f">>> Downloading file name: {name}, href: {href}")
            # open document page
            r = session.get(href)
            # get file path
            # check for attibute, if not, file doesn't exist: contact admin. but how to contact the hospital admin?
            if hasattr(re.search("(?<=window.open\\(')(.*)(?=',)", r.text), 'group'):
                file_path = re.search("(?<=window.open\\(')(.*)(?=',)", r.text).group(0)
                print(file_path)
                file_name = file_path.split("/")[-1]
                # get file and save
                r = session.get(f"{base_url}/{file_path}")
                with open('C:\\Users\\tender_documents\\'+ today_yyMMddhh + '\\' + file_name, 'wb') as f:
                    f.write(r.content)
            else:
                print(f">>> File name: {name}, href: {href}", " is missing")
                continue

【问题讨论】:

  • 我遍历了您示例中的所有网址,但无法重现该问题。我连接到每个网址。
  • 抱歉,网站不断更新网址。我已经用最新的网址更新了上面的网址。

标签: python selenium beautifulsoup python-requests


【解决方案1】:

这只是一个错字,您正在尝试使用整个正则表达式匹配:

        r = session.get(f"{base_url}/{file_path}")

应该是

        r = session.get(f"{base_url}/{file_name}")

【讨论】:

  • 如果我使用文件名,文件实际上是空的。它们都有 1KB 大小。
  • 你能告诉我们f"{base_url}/{file_name}"r.status_code的值吗
  • r.status_code 为 200,base_url/file_name 将给出实际文档路径的路径。
猜你喜欢
  • 2014-05-16
  • 1970-01-01
  • 2018-02-12
  • 2021-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多