首页 > 解决方案 > 如何在没有 for 循环的情况下抓取 url 列表?

问题描述

我有一批 url 列表,我想爬取这些 url 上的一些信息

daa = ['https://old.reddit.com/r/Games/comments/a2p1ew/', 'https://old.reddit.com/r/Games/comments/9zzo0e/', 'https://old.reddit.com/r/Games/comments/a31a6q/', ]

for y in daa:
uClient = requests.get(y, headers = {'User-agent': 'your bot 0.1'})
page_soup = soup(uClient.content, "html.parser")
time= page_soup.findAll("p", {"class":"tagline"})[0].time.get('datetime').replace('-', '')

我工作得很好,可以得到time我想要的一切。但是我需要在没有 for 循环的情况下执行此操作,或者我的意思是我需要open在下一步编写一个文件,但如果我在同一个循环中执行此操作,则输出很奇怪。time没有for循环如何获得?

标签: python-3.xlistfor-loopbeautifulsoup

解决方案


您可以按照上述方式使用open(file, 'a'). 或者我喜欢做的是将所有内容附加到一个表中,然后将整个内容写入一个文件。

import requests
import bs4 
import pandas as pd


results = pd.DataFrame()

daa = ['https://old.reddit.com/r/Games/comments/a2p1ew/', 'https://old.reddit.com/r/Games/comments/9zzo0e/', 'https://old.reddit.com/r/Games/comments/a31a6q/', ]

for y in daa:
    w=1
    uClient = requests.get(y, headers = {'User-agent': 'your bot 0.1'})
    page_soup = bs4.BeautifulSoup(uClient.content, "html.parser")
    time= page_soup.findAll("p", {"class":"tagline"})[0].time.get('datetime').replace('-', '')

    temp_df = pd.DataFrame([[y, time]], columns=['url','time'])
    results = results.append(temp_df).reset_index(drop = True)

result.to_csv('path/to_file.csv', index=False) 

推荐阅读