如何在没有for循环的情况下抓取网址列表?

问题描述 投票:-1回答:1

我有一批网址列表,我想抓取这些网址上的一些信息

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并在下一步写一个文件但如果我在同一个循环中这样做,输出很奇怪。如何在没有for循环的情况下获得time

python-3.x list for-loop beautifulsoup
1个回答
0
投票

你可以如上所述使用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) 
© www.soinside.com 2019 - 2024. All rights reserved.