Python HTTPConnectionPool无法建立新连接:[Errno 11004] getaddrinfo失败

10

我在想我的请求是否被网站拦截了,需要设置代理。我尝试关闭http连接,但是失败了。我还尝试测试我的代码,但是现在似乎没有输出。也许我使用代理就可以解决问题?这是代码:

import requests
from urllib.parse import urlencode
import json
from bs4 import BeautifulSoup
import re
from html.parser import HTMLParser
from multiprocessing import Pool
from requests.exceptions import RequestException
import time


def get_page_index(offset, keyword):
    #headers = {'User-Agent':'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50'}
    data = {
        'offset': offset,
        'format': 'json',
        'keyword': keyword,
        'autoload': 'true',
        'count': 20,
        'cur_tab': 1
    }
    url = 'http://www.toutiao.com/search_content/?' + urlencode(data)
    try:
        response = requests.get(url, headers={'Connection': 'close'})
        response.encoding = 'utf-8'
        if response.status_code == 200:
            return response.text
        return None
    except RequestException as e:
        print(e)

def parse_page_index(html):
    data = json.loads(html)
    if data and 'data' in data.keys():
        for item in data.get('data'):
            url = item.get('article_url')
            if url and len(url) < 100:
                yield url

def get_page_detail(url):
    try:
        response = requests.get(url, headers={'Connection': 'close'})
        response.encoding = 'utf-8'
        if response.status_code == 200:
            return response.text
        return None
    except RequestException as e:
        print(e)

def parse_page_detail(html):
    soup = BeautifulSoup(html, 'lxml')
    title = soup.select('title')[0].get_text()
    pattern = re.compile(r'articleInfo: (.*?)},', re.S)
    pattern_abstract = re.compile(r'abstract: (.*?)\.', re.S)
    res = re.search(pattern, html)
    res_abstract = re.search(pattern_abstract, html)
    if res and res_abstract:
        data = res.group(1).replace(r".replace(/<br \/>|\n|\r/ig, '')", "") + '}'
        abstract = res_abstract.group(1).replace(r"'", "")
        content = re.search(r'content: (.*?),', data).group(1)
        source = re.search(r'source: (.*?),', data).group(1)
        time_pattern = re.compile(r'time: (.*?)}', re.S)
        date = re.search(time_pattern, data).group(1)
        date_today = time.strftime('%Y-%m-%d')
        img = re.findall(r'src=&quot;(.*?)&quot', content)
        if date[1:11] == date_today and len(content) > 50 and img:
            return {
                'title': title,
                'content': content,
                'source': source,
                'date': date,
                'abstract': abstract,
                'img': img[0]
            }

def main(offset):
    flag = 1
    html = get_page_index(offset, '光伏')
    for url in parse_page_index(html):
        html = get_page_detail(url)
        if html:
            data = parse_page_detail(html)
            if data:
                html_parser = HTMLParser()
                cwl = html_parser.unescape(data.get('content'))
                data['content'] = cwl
                print(data)
                print(data.get('img'))
                flag += 1
                if flag == 5:
                    break



if __name__ == '__main__':
    pool = Pool()
    pool.map(main, [i*20 for i in range(10)])

错误就在这里!

HTTPConnectionPool(host='tech.jinghua.cn', port=80): Max retries exceeded with url: /zixun/20160720/f191549.shtml (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x00000000048523C8>: Failed to establish a new connection: [Errno 11004] getaddrinfo failed',))

顺便说一下,当我第一次测试我的代码时,它显示一切都很好!提前感谢!


我再次测试我的代码。我得到了输出,但当遇到HTTPConnectionPool错误时会停止,有没有办法解决这个中断。谢谢。 - cwl
5个回答

17

看起来你的HTTPConnectionPool连接数已经达到上限,因为你同时启动了10个线程。

可以尝试以下其中一种方法:

  1. 增加请求超时时间(单位:秒):requests.get('url',timeout=5)
  2. 关闭响应:Response.close()。 不要直接返回response.text,而是将response赋值给一个变量,关闭Response,然后返回变量。

response.close() - Fermi-4

4
当我面临这个问题时,我遇到了以下问题
我无法完成以下操作: - requests python 模块无法从任何 url 获取信息。虽然我能够使用浏览器浏览该网站,也可以使用 wget 或 curl 下载该页面。 - pip 安装也不起作用,并出现以下错误
“Failed to establish a new connection: [Errno 11004] getaddrinfo failed”
某些网站阻止了我的访问,所以我尝试使用 forcebindip 来为我的 python 模块使用另一个网络接口,然后我将其删除。可能导致我的网络混乱,我的请求模块甚至直接的 socket 模块都被卡住,无法获取任何 url。
因此,我按照下面 URL 中的网络配置重置进行操作,现在一切正常。 network configuration reset

1

如果有人需要帮助,我也遇到了同样的错误信息:

Client-Request-ID=long-string Retry policy did not allow for a retry: , HTTP status code=Unknown, Exception=HTTPSConnectionPool(host='table.table.core.windows.net', port=443): Max retries exceeded with url: /service(PartitionKey='requests',RowKey='9999') (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x000001D920ADA970>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed')).

当尝试使用 table_service.get_entity(table_name, partition_key, row_key) 从 Azure 表存储中检索记录时...

我的问题:

  • 我错误地定义了 table_name

0
有时候这是由于 VPN 连接引起的。我曾经遇到过同样的问题。我甚至无法通过 pip 安装 requests 包。我关闭了 VPN,然后就成功安装了它并且可以发送请求了。错误代码 [Errno 11004] 不再出现了。

-1

我的结构化URL不正确(在“.com”之后没有斜杠,而且还有另一部分URL的耦合)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接