python - 虽然循环在 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
行。
任何帮助我将不胜感激!
解决方案
根据我们的要求设置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
推荐阅读
- python - recursively go through list to calculate the percentage change between two items at every n elements
- vue.js - strange behavior when trying to re-render data inside slot in vue
- docker - In which folder is data of volumes in Docker Windows stored?
- git - Jenkins pipeline fails git clone using sshagent plugin?
- angular - application Error net::err_proxy_connection_faild (http://192.168.43.162)
- java - 迭代流时出现 NullPointerException
- android - How I can show my android constrain layout chain icon hints, I did not show this feature in my layout. I am using android version 3.5.2
- python - 如何在keras的LSTM自动编码器中获取middel层的输出
- css - 在 CSS 中使用 Flex 属性集中文本
- vue.js - Life cycle Hook in vueJs