python - WebElement 和 __getitem__ 有什么问题
问题描述
我正在尝试收集 google 搜索页面的标题和链接,我正在使用 selenium。我使用 xpath 填充字段并单击按钮。
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import pandas as pd
browser = webdriver.Chrome(executable_path ='c:\\chromedriver.exe')
browser.get('https://www.google.com')
search_bar_xpath=browser.find_element_by_xpath('//* [@id="tsf"]/div[2]/div/div[1]/div/div[1]/input')
search_bar_xpath.send_keys('mybirthday')
search_button = browser.find_element_by_xpath('//*[@id="tsf"]/div[2]/div/div[3]/center/input[1]')
search_button.click()
search_results= browser.find_elements_by_xpath('//*[@id="rso"]/div[2]/div/div[2]/div/div/div[1]')
scrap_data=[]
for search_result in search_results:
title = search_result.text.encode('utf8')
link = search_result['href']
scrap_data.append(title,link)
我收到此消息错误:
TypeError Traceback (most recent call last)
<ipython-input-15-3341663b53f6> in <module>()
2 for search_result in search_results:
3 title = search_result.text.encode('utf8')
----> 4 link = search_result['href']
5 scrap_data.append(title,link)
TypeError: 'WebElement' object has no attribute '__getitem__'
解决方案
你错了:
link = search_result['href']
可能你需要.get_attribute
这样:
link = search_result.get_attribute('href')
推荐阅读
- ruby-on-rails - Rails 中电话号码的自定义验证
- python - 将数据框的两列与新的数据框列进行比较
- c# - Angular 将 json 字符串转换为类型化数组
- html - 如何从 json 数据中检索数据
- excel - 解析 word docx 文件以将特定标题段落复制到 xlsx excel 文件中
- javascript - 如何在 node.js 中加载 CSS 文件?
- android - 未找到资源崩溃。该项目根本不包含对 design_ic_visibility 文件的引用
- redirect - URL 仅重写 html 页面
- laravel - 中间件中的 Null Auth 用户
- outlook-redemption - 读取创建日期和接收日期的兑换错误