【发布时间】:2021-09-11 15:49:55
【问题描述】:
您好,我一直在使用 python 脚本来收集结果列表并将这些结果写入 csv 文件。
我的代码有效,但它会将结果写入一个单元格(由“~”连接)。我想将每个结果写入一个新行。
我没有太多经验,但我确实在我的能力范围内进行了搜索。如果您觉得好像有什么东西在躲避我,请告诉我我应该一直在寻找什么吗?
这是我当前的代码:
person_result_names = WebDriverWait(browser, 60, ignored_exceptions=ignored_exceptions).until(EC.visibility_of_element_located((By.ID, 'person_results'))).find_elements_by_css_selector("#person_info > div > div > div.name.variation")
wait_time(1)
all_persons = [ person.text.replace(',', '').replace('\n', ' ') for person in person_result_names ]
print(f"[**] Found {len(all_persons)} people")
person = '~'.join(all_persons)
print(person)
report_links = browser.find_elements_by_css_selector('#person_results > div > a')
all_urls = [ url.get_attribute('href') for url in report_links ]
print(f"[**] Found {len(all_urls)} report urls")
url = '~'.join(all_urls)
print(url)
time.sleep(5)
with open('3_results-output.csv', 'a') as fp:
print(f"{row_id},{person},{url}", file=fp)
不用担心最后一行的row_id 变量。它是从另一个来源拉出来的。提前感谢所有有用的解决方案。
这是我当前的输出:
ID 表示每个搜索查询,因此ID 0 对于名称和网址都有 3 个结果。 ID 1 每个有 4 个结果
ID | Names | Urls
0 | John Doe~Joe Doe~Jay Doe | http://www.link.com/1~http://www.link.com/2~http://www.link.com/3
1 | Jane Doe~Janet Doe~Jill Doe~Julia Doe | http://www.link.com/4~http://www.link.com/5~http://www.link.com/6~http://www.link.com/7
这是我希望输出的样子:
ID | Names | Urls
0 | John Doe | http://www.link.com/1
0 | Joe Doe | http://www.link.com/2
0 | Jay Doe | http://www.link.com/3
1 | Jane Doe | http://www.link.com/4
1 | Janet Doe | http://www.link.com/5
1 | Jill Doe | http://www.link.com/6
1 | Julia Doe | http://www.link.com/7
更新
这是最终为我工作的代码。感谢@Tim Post 为我指明了正确的方向。我只需要包含所有结果的写作方法。下面的代码对我有用:
person_result_names = WebDriverWait(browser, 60, ignored_exceptions=ignored_exceptions).until(EC.visibility_of_element_located((By.ID, 'person_results'))).find_elements_by_css_selector("#person_info > div > div > div.name.variation")
wait_time(1)
print("\tScraping People\n")
all_persons = [ person.text.replace(',', '').replace('\n', ' ') for person in person_result_names ]
print(f"[**] Found {len(all_persons)} people")
wait_time(1)
report_links = browser.find_elements_by_css_selector('#person_results > div > a')
all_urls = [ url.get_attribute('href') for url in report_links ]
print(f"[**] Found {len(all_urls)} report urls")
with open('3_results-output.csv', 'a') as fp:
for person, url in zip(all_persons, all_urls):
print(f"{row_id},{person},{url}", file=fp)
【问题讨论】:
-
您好!欢迎来到本站。我已经修改了与您的经验水平相关的答案中的措辞,因此它指出了有用的人可以根据需要做的事情。另外,我从其他人那里删除了很多居高临下的 cmets - 很抱歉您经历过这种情况,这不是我们。
-
@TimPost 谢谢。我将继续使用这种方法。非常感谢:)