python-3.x - 如何在没有 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循环如何获得?
解决方案
您可以按照上述方式使用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)
推荐阅读
- javascript - 为什么右键单击事件比左键慢?
- python - 有没有办法在python中重置列表的值?
- sql - 如何计算 Hive 表中人员之间协议的重叠百分比
- mysql - 以 laravel 查询或雄辩的方式获得所需结果的最佳方法
- mqtt - MQTT发布和订阅,来自同一设备的不同主题?
- python - Specify format(s) of text copied from Qt app? Somehow crashes other app when pasted
- javascript - What is the maximum value of a Float32Array?
- c# - Binding image in listview
- github - 什么是 github 操作分钟/月?
- c - How can a client deliberately trigger an accept error on a TCP server written in C?