Python Web Scraping - 只查找 n 个项目

我正在运行一个用 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无论如何都会包含比我需要的更多的元素。


你能帮我理解我所缺少的吗?


慕妹3242003
浏览 91回答 1
1回答

子衿沉夜

您的代码中有一个双循环。要退出这两个循环,您需要使用break两次,每个循环一次。您可以在两个循环中的相同条件下中断。试试这个代码:import reimport bs4,requestskeyword_list = ['health','Coronavirus','travel']articles_list = []base_url = 'https://news.google.com/search?q=TEST%20when%3A3d&hl=en-US&gl=US&ceid=US%3Aen'&nbsp;request = requests.get(base_url)&nbsp;webcontent = bs4.BeautifulSoup(request.content,'lxml')&nbsp;maxcnt = 5&nbsp; # max number of articles&nbsp; &nbsp; &nbsp;for ictr,i in enumerate(webcontent.findAll('div',{'jslog':'93789'})):&nbsp; &nbsp;if len(articles_list) == maxcnt: break&nbsp; &nbsp;# exit outer loop&nbsp; &nbsp;for link in i.findAll('a', attrs={'href': re.compile("/articles/")},limit=1):&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;if any(keyword in i.select_one('h3').getText() for keyword in keyword_list):&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;articles_list.append((i.select_one('h3').getText(),"https://news.google.com"+str(link.get('href'))))&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if len(articles_list) == maxcnt: break&nbsp; # exit inner loopprint(str(len(articles_list)), 'articles')print('\n'.join(['> '+a[0] for a in articles_list]))&nbsp; # article titles输出5 articles> Why Coronavirus Tests Come With Surprise Bills> It’s Not Easy to Get a Coronavirus Test for a Child> Britain’s health secretary says the asymptomatic don’t need tests. Critics say that sends a mixed message.> Coronavirus testing shifts focus from precision to rapidity> Coronavirus testing at Boston lab suspended after nearly 400 false positives
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python