Не удается устранить ошибку HTTP 429 с помощью time.sleep () - PullRequest
0 голосов
/ 27 февраля 2020

Мне нужно почистить ссылки на результаты поиска Google.

Однако, я продолжаю получать ошибку http 429, даже если в свой код добавлен time.sleep ().

Он работает для 50 - 100 строк, затем выдает ошибку 429. Но есть сотни ссылок на штрих-коды, которые мне нужно почистить.

Как я могу решить эту проблему?

import time
from itertools import chain

import pandas as pd
import requests
from bs4 import BeautifulSoup

barcode_df = pd.read_csv("C:/Users/emina/Coding_Projects/PycharmProjects/drug_interaction(pycharm)/barcodes.csv")
barcode_list2d = barcode_df.values.tolist()    
barcode_list = list(chain.from_iterable(barcode_list2d))  # This is the list we'll iterate over    
barcode_list = [x for x in barcode_list if type(x) == str]
barcode_list_deneme = barcode_list[0:20]    
barcode_list1 = barcode_list[0:1000]

USER_AGENT = "some user agent"
headers = {"user-agent": USER_AGENT}


def append_links_to_csv(barcode):
    if resp.status_code == 200:
        soup = BeautifulSoup(resp.content, "html.parser")
        for g in soup.find_all('div', class_='r'):
            anchors = g.find_all('a')
            if anchors:
                link = anchors[0]['href']  # Parses search link
                l.write(barcode + "," + link + "\n")
            time.sleep(0.06)
    else:
        print(resp.status_code)


count = 0 


l = open("links.csv", "a")

for barcode in barcode_list1:

    query = barcode + "+" + "site:ilacabak.com"
    url = f"https://google.com/search?q={query}"        
    resp = requests.get(url, headers=headers)
    append_links_to_csv(barcode)
    count += 1
    print(count)        
    time.sleep(1.5)

    if count % 100 == 0:
        l.close()
        l = open("links.csv", "a")
l.close()
...