首页 > 解决方案 > 多个 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()

标签: pythonpython-2.7web-scrapingbeautifulsoup

解决方案


谢谢托马斯,实际上我通过思考如何使它更简单来稍微调整我的代码(四个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()

推荐阅读