python - 如何在 Python (BeaufitulSoup) 中在 CSV 中为多网址刮板附加新行?
问题描述
我对 Python 很陌生,我正在测试我的第一个爬虫(使用我在这里和那里找到的一些代码)。我能够使用所需的所有信息编写 CSV,但现在我尝试输入超过 1 个 URL,而脚本只是编写我在数组中插入的最后一个 URL,就像不是附加新 URL 而只是重新写在相同的第一个原始文件上。
我到处寻找并尝试了很多东西,但我想我需要一些帮助,谢谢!
from bs4 import BeautifulSoup
import requests
from csv import writer
urls = ['https://example.com/1', 'https://example.com/2']
for url in urls:
my_url = requests.get(url)
html = my_url.content
soup = BeautifulSoup(html,'html.parser')
info = []
print (urls)
lists = soup.find_all('div', class_="profile-info-holder")
links = soup.find_all('a', class_="intercept")
with open('multi.csv', 'w', encoding='utf8', newline='') as f:
thewriter = writer(f)
header = ['Name', 'Location', 'Link', 'Link2', 'Link3']
thewriter.writerow(header)
for list in lists:
name = list.find('div', class_="profile-name").text
location = list.find('div', class_="profile-location").text
social1 = links[0]
social2 = links[1]
social3 = links[2]
info = [name, location, social1.get('href'),social2.get('href'),social3.get('href')]
thewriter.writerow(info)
解决方案
基本方法
- 以附加模式 ('a') 打开文件。
- 将光标指向文件末尾。
- 使用 write() 函数在文件末尾追加 '\n'
- 使用 write() 函数将给定的行附加到文件中。
- 关闭文件。
--
with open('multi.csv', 'a', encoding='utf8', newline='') as f:
您可能必须以另一种方式排列循环,但没有urls
它很难描述:
from bs4 import BeautifulSoup
import requests
from csv import writer
urls = ['https://example.com/1', 'https://example.com/2']
with open('multi.csv', 'a', encoding='utf8', newline='') as f:
thewriter = writer(f)
header = ['Name', 'Location', 'Link', 'Link2', 'Link3']
thewriter.writerow(header)
for url in urls:
my_url = requests.get(url)
html = my_url.content
soup = BeautifulSoup(html,'html.parser')
info = []
lists = soup.find_all('div', class_="profile-info-holder")
for l in lists:
name = l.find('div', class_="profile-name").text
location = l.find('div', class_="profile-location").text
links = l.find_all('a', class_="intercept")
social1 = links[0]
social2 = links[1]
social3 = links[2]
info = [name, location, social1.get('href'),social2.get('href'),social3.get('href')]
thewriter.writerow(info)
推荐阅读
- eclipse - 无法通过代理在 Eclipse 中创建 Maven 项目
- sql-server - 记录新记录时删除旧记录
- java - Mybatis - 关闭连接时出错
- python - 我的联系表格在 django 中无法正常工作?
- ios - Objective-c 中的空格
- mysql - Rails - SQL - 连接和 COALESCE
- python - 从数据集/数据数组索引非连续时间序列
- android - 合并 PagedListAdapter 的多个数据源
- docker - Hyperledger Composer - NetworkAdmin#admin 对网络没有读取权限
- c# - 如何使用默认值更新为空的 Datatable 列值