python 3.x-当通过for循环将字典附加到列表时,我只得到最后一个字典



我试图通过浏览所有不同的页面来抓取一个职业搜索网站,当我试图使用for循环将字典附加到列表中时,我一直遇到问题。当我在Python 3.4中执行下面的代码时,代码会将每个页面中的所有相关数据拉到一个字典中(我已经用print()进行了检查),并附加到"FullJobDetails"中,但在for循环结束时,我得到了一个列表,其中只包含最后一页中的字典。字典的数量与列表"ListofJobs"中的页数完全相同。"ListofJobs"是我正在废弃的每个页面的html链接列表。

我刚开始学习代码,所以我知道下面的代码在任何形式、方式或形式上都不是最有效或最好的方法。任何建议都将不胜感激。提前感谢!

FullJobDetails = []
browser = webdriver.Chrome()
dictionary = {}
for jobs in ListofJobs:
  browser.get(jobs)
  dictionary["Web Page"] = jobs
  try:
    dictionary["Views"] = browser.find_element_by_class_name('job-viewed-item-count').text
  except NoSuchElementException:
    dictionary["Views"] = 0
  try:
    dictionary['Applicants'] = browser.find_element_by_class_name('job-applied-item-count').text
  except NoSuchElementException:
    dictionary["Applicants"] = 0
  try:
    dictionary["Last Application"] = browser.find_element_by_class_name('last-application-time-digit').text
  except NoSuchElementException:
    dictionary["Last Application"] = "N/A"
  try:
    dictionary["Job Title"] = browser.find_element_by_class_name('title').text
  except NoSuchElementException:
    dictionary["Job Title"] = "N/A"
  try:
    dictionary['Company'] = browser.find_element_by_xpath('/html/body/div[3]/article/section[2]/div/ul/li[4]/span/span').text
  except NoSuchElementException:
    dictionary['Company'] = "Not found"
  try:
    dictionary['Summary'] = browser.find_element_by_class_name('summary').text
  except NoSuchElementException:
    dictionary['Summary'] = "Not found"
  FullJobDetails.append(dictionary)

问题是,您只创建了一个字典-字典是可变对象-相同的附加条件会一次又一次地附加到您的列表中,并且在每次for循环中都会更新其内容。因此,在最后,您将拥有同一个切片的多个副本,所有副本都显示了最后一页的信息。

只需为每次运行for循环创建一个新的dictionary对象。新字典将保存在列表中,变量名dictionary可以毫无冲突地容纳新对象。

for jobs in ListofJobs:
  dictionary = {} 
  browser.get(jobs)
  ...

最新更新