【问题标题】:Python Mechanize/BeautifulSoup Scraping (Iterating over Dictionaries)Python Mechanize/BeautifulSoup Scraping(迭代字典)
【发布时间】:2015-01-01 15:30:51
【问题描述】:

我目前正在使用 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”所在的下方表格中,然后将其附加到另一个字典或将其写入 csv。

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

【问题讨论】:

  • 我不确定问题代码是否实际显示在代码示例中。好像没有?
  • 您能否扩展并澄清您所说的“我正在尝试使用'id'进行迭代,将其放入'licenseNumber'所在的下方表格中,然后将其附加到另一个字典或编写它到 csv"?
  • 下面的答案有帮助吗?你能进一步解释你的问题吗?

标签: python loops web-scraping beautifulsoup mechanize


【解决方案1】:

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

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

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

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

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

【讨论】:

    猜你喜欢
    • 2013-12-03
    • 1970-01-01
    • 1970-01-01
    • 2018-04-02
    • 1970-01-01
    • 2014-05-29
    • 2014-10-02
    • 2021-07-24
    • 2018-04-06
    相关资源
    最近更新 更多