首页 > 解决方案 > 虽然循环在 Beautiful Soup 期间突然停止挖掘但过程继续无休止?

问题描述

我正在使用 Selenium 和 Beautiful Soup 创建一个用于网络抓取新闻的模板。

我创建了一个 DataFrame,其中有一列包含我想从我选择测试的网站上抓取的所有链接。我实现了隔离post id, date, author, title, subtitle and text

现在我正在尝试遍历我的 url 列并post id, date, author, title, subtitle and text用每一行的每个值填充其他空列 ( )。

我做了一个测试100 rows,它工作得很好。但是,如果我尝试使用所有行 ( 41327) Jupyter Notebook 只需停止挖掘(我可以使用 进行检查TQDM),但该过程不会中断。我不知道网站是否阻止了我(我不会收到错误吗?),我认为这不是问题,因为如果我重新运行代码,它会立即再次工作,直到它发生相同的情况。

我的代码有什么问题吗?

我创建并用于网络抓取的功能:

def full_table():
    j=0
    while tqdm(j<=41327):
        try:
            url = df[0][j]
            response = requests.get(url)
            html = response.content
            soup = BeautifulSoup(html, 'html.parser') 
            corpus  = (soup.find("article")).findAll('p')
            title = soup.find_all('h1')[1].text
            df['title'].iloc[j] = title
            subtitle = soup.find_all('h2')[0].text
            df['subtitle'].iloc[j] = subtitle
            date = soup.find(class_="author").find_all("span")[-1].get_text(strip=True)
            df['date'].iloc[j] = date
            author = soup.find(class_="author").span.get_text(strip=True)
            df['author'].iloc[j] = author
            news_id  = (soup.find("article"))["id"]
            df['news_id'].iloc[j] = news_id
            text = article(corpus)
            df['text'].iloc[j] = text          
            j+=1
        #print(df)
        except:
            j+=1
            pass
    print(df)
    return df

我从 TQDM 得到的最后一件事是:

0it [00:00, ?it/s]
0it [00:13, ?it/s]
0it [00:00, ?it/s]

00:13是一个奇怪的,以前都是一样的,正如我所说,如果我尝试使用,100 rows我会得到一个完美的 DataFrame 和我需要的东西。现在我需要获取所有41327行。

任何帮助我将不胜感激!

标签: pythonloopsweb-scrapingwhile-looppython-requests

解决方案


根据我们的要求设置timeout=10解决了这个问题。

def full_table():
    j=0
    while tqdm(j<=41327):
        try:
            url = df[0][j]
            response = requests.get(url, timeout=10)
            html = response.content
            soup = BeautifulSoup(html, 'html.parser') 
            corpus  = (soup.find("article")).findAll('p')
            title = soup.find_all('h1')[1].text
            df['title'].iloc[j] = title
            subtitle = soup.find_all('h2')[0].text
            df['subtitle'].iloc[j] = subtitle
            date = soup.find(class_="author").find_all("span")[-1].get_text(strip=True)
            df['date'].iloc[j] = date
            author = soup.find(class_="author").span.get_text(strip=True)
            df['author'].iloc[j] = author
            news_id  = (soup.find("article"))["id"]
            df['news_id'].iloc[j] = news_id
            text = article(corpus)
            df['text'].iloc[j] = text          
            j+=1
        #print(df)
        except:
            j+=1
            pass
    print(df)
    return df

推荐阅读