python - 多个 for 循环和 csv 文件
问题描述
我是新来的python新手,目前正在学习一些基本的东西,主要是爬虫,我遇到了一个问题,希望你能帮我解决。
我试图从网站上抓取一些细节并将它们写入 CSV 文件,但我只能将最后的结果写入我的 CSV,显然我的脚本只是覆盖了数据。
此外,如果您在我的代码中发现任何错误或任何改进空间(我确信有),如果您也能指出它们,我会很高兴。
Also2,任何可以帮助我提高 python 和抓取技能的视频/教程推荐将不胜感激。
import requests
from bs4 import BeautifulSoup
import csv
url = 'https://www.tamarackgc.com/club-contacts'
source = requests.get(url).text
soup = BeautifulSoup (source, 'lxml')
csv_file = open('contacts.csv', 'w')
csv_writer = csv.writer (csv_file)
csv_writer.writerow(["department", "name", "position", "phone"])
for department in soup.find_all("div", class_="view-content"):
department_name = department.h3
print (department_name.text)
for contacts in soup.find_all("div", class_="col-md-7 col-xs-10"):
contact_name = contacts.strong
print(contact_name.text)
for position in soup.find_all("div", class_="field-content"):
print(position.text)
for phone in soup.find_all("div", class_="modal-content"):
first_phone = phone.h3
first_phones = first_phone
print(first_phones)
csv_writer.writerow([department_name, contact_name, position, first_phones])
csv_file.close()
解决方案
谢谢托马斯,实际上我通过思考如何使它更简单来稍微调整我的代码(四个for循环太多了,不是吗?)所以用下面的代码我解决了我的问题(放弃了'部门'和'电话'因为其他一些问题):
import requests
from bs4 import BeautifulSoup
import csv
url = 'https://www.tamarackgc.com/club-contacts'
source = requests.get(url).text
soup = BeautifulSoup (source, 'lxml')
f = open("contactslot.csv", "w+")
csv_writer = csv.writer (f)
csv_writer.writerow(["Name", "Position"])
infomation = soup.find_all("div", class_="well profile")
info = information[0]
for info in information:
contact_name = info.find_all("div", class_="col-md-7 col-xs-10")
names = contact_name[0].strong
name = names.text
print (name)
position_name = info.find_all("div", class_="field-content")
position = position_name[0].text
print(position)
print("")
csv_writer.writerow([name, position])
f.close()
推荐阅读
- python - 在 python 中将 mXnXk 矩阵绘制为 3d 模型
- android - 最初设置后无法更改应用栏标题的可见性
- python - 我正在尝试编写一个正则表达式来捕获特定的单词替换它
- dart - Dart 隔离 SendPort 和 ReceivePort 发送 100 次,反之亦然
- postgresql - 我应该如何在 Postgres 中存储 Go 的 time.Location?
- sql - 如何检查重复的 CLOB - Oracle?
- python - 旋转框小部件内的变量,可在单击按钮小部件时显示在 LCD 小部件中
- reactjs - 如何计算渲染函数中的行数?
- c# - 如何在 GetEnumerator 中返回动态实体
- sql - 在 SQL Developer 的脚本中传递和使用参数