我正在运行一个用 Beautiful Soup 制作的抓取脚本。我从 Google 新闻中抓取结果,并且只想获取作为元组添加到变量中的前 n 个结果。该元组由新闻标题和新闻链接组成。在完整的脚本中,我有一个关键字列表,例如 ['crisis','finance'] 等,您可以忽略该部分。这就是代码。
import bs4,requests
articles_list = []
base_url = 'https://news.google.com/search?q=TEST%20when%3A3d&hl=en-US&gl=US&ceid=US%3Aen'
request = requests.get(base_url)
webcontent = bs4.BeautifulSoup(request.content,'lxml')
for i in webcontent.findAll('div',{'jslog':'93789'}):
for link in i.findAll('a', attrs={'href': re.compile("/articles/")},limit=1):
if any(keyword in i.select_one('h3').getText() for keyword in keyword_list):
articles_list.append((i.select_one('h3').getText(),"https://news.google.com"+str(link.get('href'))))
这样写就是将满足 if 语句的所有新闻和链接添加为元组,这可能会导致一个很长的列表。我只想获取前 n 条新闻,假设有 5 条,然后我希望脚本停止。
我试过:
for _
in range(5):
但我不明白在哪里添加它,因为代码要么没有运行,要么附加相同的新闻 5 次。
我也尝试过:
while len(articles_list)<5:
但由于该语句是 for 循环的一部分,并且变量articles_list 是全局的,因此它也停止为下一个抓取对象追加内容。
最后我尝试了:
for tuples in (articles_list[0:5]): #Iterate in the tuple,
for element in tuples: #Print title, link and a divisor
print(element)
print('-'*80)
如果没有其他选择,我可以做最后一个,但我会避免,因为变量articles_list无论如何都会包含比我需要的更多的元素。
你能帮我理解我所缺少的吗?
子衿沉夜
相关分类