【问题标题】:Adding values from a list into a dictionary将列表中的值添加到字典中
【发布时间】:2022-11-05 19:14:51
【问题描述】:

我创建了一个循环,使用 Chromedriver 抓取网站数据(交易 ID 和目的地)并将它们添加到列表中。我想将交易 ID 与从目标表中获取的值配对并将它们添加到字典中。每个网站抓取迭代都有不同数量的目的地(有时多达 20 个),但只有一个交易 ID。

我希望我的字典的输出类似于:

dicts = {'Deal ID #123': ['Lisbon, Portugal', Seville, Spain'], 'Deal ID #456' : ['Monte Carlo, Monaco', 'Marseille, France', 'Istanbul, 
Turkey', 'Myrina (Limnos), Greece']}

到目前为止,这是代码:

dicts = {}
fast_deal_list = []
table_data = []


for link in urllistsmall:
    driver = webdriver.Chrome(r"C:\Users\me\chromedriver.exe")
    driver.get(link)
    driver.find_element_by_name("LogEmail").send_keys(username)
    driver.find_element_by_css_selector("#MemberForm .btn").click()
    soup = BeautifulSoup(driver.page_source, "html.parser")
   
    for fast_deal_x in soup.find('h1'):
        fast_ids = fast_deal_x.get_text()
        fast_deal_list.append(fast_ids)
    
        for table_x in soup.find_all(target="_blank"):
            table_data_run = table_x.get_text()
            table_data.append(table_data_run)

【问题讨论】:

  • 不要使用fast_deal_listtable_data,而是直接创建dicts[fast_ids] = [] 并附加到dicts[fast_ids]
  • 更好地显示真实的 url,这样我们就可以看到真实的 HTML。
  • 这是我正在抓取的网站之一的示例:vacationstogo.com/fastdeal.cfm?deal=27669&sp=y

标签: python list dictionary for-loop selenium-chromedriver


【解决方案1】:

您可以使用此代码 dicts['Deal ID #123'] = ['里斯本,葡萄牙',塞维利亚,西班牙'] dicts['Deal ID #456'] = ['Monte Carlo, Monaco', 'Marseille, France', 'Istanbul, Turkey', 'Myrina (Limnos), Greece']

【讨论】:

    猜你喜欢
    • 2015-04-02
    • 1970-01-01
    • 1970-01-01
    • 2018-08-27
    • 1970-01-01
    • 2023-02-26
    • 2021-01-26
    • 1970-01-01
    • 2023-03-23
    相关资源
    最近更新 更多