【发布时间】:2019-08-04 16:58:55
【问题描述】:
我是新来的python新手,目前正在学习一些基本的东西,主要是爬虫,我遇到了一个问题,希望你能帮我解决。
我试图从网站上抓取一些细节并将它们写入 CSV 文件,但我只能将最后的结果写入我的 CSV,显然我的脚本只是覆盖了数据。
此外,如果您在我的代码中发现任何错误或任何改进空间(我确信有),我会很高兴您也指出它们。
此外,任何可以帮助我提高 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()
【问题讨论】:
-
你的线索在方法名
csv_writer.writerow([department_name, contact_name, position, first_phones])中。writerow写一行,你调用一次。例如,department_name的值在for department in soup.find_all("div", class_="view-content"):中经历了它可能拥有的所有化身,没有写入,剩下的就是它的最后一个化身。
标签: python python-2.7 web-scraping beautifulsoup