簡體   English   中英

Python HTTPConnectionPool 無法建立新連接:[Errno 11004] getaddrinfo failed

[英]Python HTTPConnectionPool Failed to establish a new connection: [Errno 11004] getaddrinfo failed

我想知道我的請求是否被網站停止了,我需要設置一個代理。我首先嘗試關閉 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 中的連接限制。 由於您同時啟動 10 個線程

嘗試以下方法之一:

  1. 增加請求超時(秒): requests.get('url', timeout=5)
  2. 關閉響應: Response.close() 不是返回 response.text,而是將 response 分配給一個變量,關閉 Response,然后返回變量

當我遇到這個問題時,我遇到了以下問題

我無法執行以下操作 - requests python 模塊無法從任何 url 獲取信息。 雖然我可以使用瀏覽器瀏覽網站,但也可以使用 wget 或 curl 來下載該頁面。 - pip install 也無法正常工作並使用失敗並出現以下錯誤

Failed to establish a new connection: [Errno 11004] getaddrinfo failed

某些站點阻止了我,所以我嘗試 forcebindip 為我的 python 模塊使用另一個網絡接口,然后我將其刪除。 可能這會導致我的網絡混亂,我的請求模塊甚至直接套接字模塊都卡住了,無法獲取任何 url。

所以我按照下面的 URL 中的網絡配置重置,現在我很好。

網絡配置重置

如果它對其他人有幫助,我會遇到同樣的錯誤消息:

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')).

...當嘗試使用 Azure 表存儲檢索記錄時

table_service.get_entity(table_name, partition_key, row_key)

我的問題:

  • 我錯誤地定義了table_name

我的結構 URL 不正確(在“.com”之后沒有斜線並且 URL 的另一部分有耦合)

有時是由於 VPN 連接造成的。 我有同樣的問題。 我什至無法通過 pip 安裝 package requests 我關閉了我的 VPN,瞧,我設法安裝了它並提出了請求。 [Errno 11004]代碼消失了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM