【发布时间】:2021-03-14 12:09:15
【问题描述】:
试图抓取一些数据。用打印检查它并获得多张打印。但是,CSV 只有一个条目。你能帮忙吗?非常感谢。
import csv
import time
import requests
from bs4 import BeautifulSoup
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
job_Details = []
job_links = []
chrome_options = Options()
'''chrome_options.add_argument("--headless")'''
driver = webdriver.Chrome(executable_path='C:/bin/chromedriver.exe', options=chrome_options)
driver.get(f'https://remotejobs.world/')
'''SCROLL_PAUSE_TIME = 20'''
last_height = driver.execute_script("return document.body.scrollHeight")
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
divs = driver.find_elements_by_tag_name('h2')
for div in divs:
job_Details.append(div)
link = div.find_element_by_tag_name('a')
job_links.append(link)
for job_detail, job_link in zip(job_Details, job_links):
if job_detail and job_link:
print(job_link.get_attribute('href'))
print(job_detail.text)
url = job_link.get_attribute('href')
new_page = requests.get(url).text
time.sleep(2)
soup = BeautifulSoup(new_page, 'html.parser')
job_desc = soup.find('div', class_='w-full md:w-2/3')
if job_desc:
print(job_desc.text) #Successful Prints.
dict = {'Job_title and Company': job_detail.text, "Job link": job_link.get_attribute('href'),
"Job Details": job_desc.text}
with open('remoteWORLD.csv', 'w') as f:
w = csv.DictWriter(f, dict.keys())
w.writeheader()
w.writerow(dict)
【问题讨论】:
-
因为您的 for 循环中有
with open('remoteWORLD.csv', 'w') as f:,所以您只会获得 CSV 文件中的最后一个条目。 -
@JustinEzequiel 当我把它移到外面时,它说 Dict 可能是未定义的?
-
你只需要
dict作为标题行并且键是固定的!我建议你重命名dict,因为它会影响内置函数。 -
@JustinEzequiel 你能检查一下吗..它正在写第三列的第一个条目..
-
查看您的
dict = {...}行。'Job_title and Company': job_detail.text和"Job Details": job_desc.text。如果这是错误的,那么您需要切换值。
标签: python python-3.x csv beautifulsoup