gpt4 book ai didi

Python Mechanize/BeautifulSoup Scraping(迭代字典)

转载 作者:行者123 更新时间:2023-12-04 16:22:50 25 4
gpt4 key购买 nike

我目前正在使用 BS 和 Mechanize 抓取一个站点,并且我能够让我的抓取器为一个实例工作,但我想遍历字典,为它循环的每种类型插入一个值。因为我对 python 完全是个菜鸟(我很抱歉),所以我无法理解如何做到这一点。

请参阅下面的代码以获取一个值:

import mechanize
import cookielib
import csv
from bs4 import BeautifulSoup as BS

ids = csv.DictReader(open("csv_to_scrape.csv"))
persons = [person for person in ids]

br = mechanize.Browser()
br2 = mechanize.Browser()
cj = cookielib.LWPCookieJar()

br.set_cookiejar(cj)
br2.set_cookiejar(cj)

br.open('https://www.example.com')

br.select_form(nr=0)
br.form['licenseNumber'] = '012345' #This is the value that comes from my dict.
br.submit()

for link in br.links(url_regex="/details"):
req = br.click_link(url=link.url)
html = br2.open(req).read()

soup = BS(html)
text1 = soup.find('div', {'class':'infobox append-bottom span-11'}).text
text2 = soup.find('div', {'class':'infobox append-bottom'}).text

f = open('output.csv', 'w')
x = '012345'
write_to_file = x + "," + '"""' + text2 + '"""' + "," + '"""' + text1 + '"""' + "\n"
write_to_unicode = write_to_file.encode('utf-8')
print x
f.write(write_to_unicode)
f.close()

我有一个基本的字典,看起来像这样:
[{'': '3008', 'name': 'Doe, John', 'date': '05-09-89', 'location': 'New York, NY', 'action': 'Dance', 'id': '012345'}, {'': '3080', 'name': 'Smith, John', 'date': '12-04-92', 'location': 'San Francisco, CA', 'action': 'Singing', 'id': '543210'}, etc.....

我正在尝试使用“id”进行迭代,将其放入下面“licenseNumber”所在的表单中,然后将其附加到另一个 dict 或将其写入 csv。

我知道这可能很容易(而且很基本),但我已经被困了两天(每天投入 10 小时)。任何帮助将不胜感激。

最佳答案

在 python 中从字典中获取一个项目非常容易。只需调用 get字典上的方法并将其传递给您想要的 key 。例如:dictionary.get(key) .在您的情况下,您的 key将是您的“身份证”。

因为您显示了一个字典列表并提到了迭代,所以这里有一行快速的代码来从您的字典列表中提取所有 id。

list_of_ids = [_dict.get("id") for _dict in list_of_dicts]

就是这样。现在您可以遍历列表并将 id 输入到表单中——这可能意味着您需要嵌套当前的 for loop但从你的代码中并不清楚,所以我不会说。

我希望这会有所帮助,如果我完全误解了您的问题,我深表歉意。

关于Python Mechanize/BeautifulSoup Scraping(迭代字典),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27732078/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com