【问题标题】:How to find child element while having found the parent div?如何在找到父 div 的同时找到子元素?
【发布时间】:2020-04-14 03:15:24
【问题描述】:

我有一个谷歌表单,我正在网页抓取(至少尝试这样做)。我想通过它查找显示“名称”的文本,然后找到包含该问题的整个块的父 div 并查找可以使用 send_keys() 填写我的姓名的输入元素。我能够找到“名称”并找到父 div。

src = result.content
driver = webdriver.Chrome()
driver.get('https://exampleform.com')
soup = BeautifulSoup(src, 'html.parser')
name = soup.find(string="Name ")
nameBlock = name.find_parents('div', class_="freebirdFormviewerViewNumberedItemContainer", limit = 1)

if soup.find(string="Name "):
  print('yes')
#prints yes

if name.find_parents('div', class_="freebirdFormviewerViewNumberedItemContainer", limit = 1):
  print('okay')

#prints okay

if nameBlock.find('input'):
  print('yup')  

#gets error

# Also have tried nameBlock.find(tag = 'input')
# and nameBlock.find_element_by_tag_name('input)
# and name.find_parents('div', class_="freebirdFormviewerViewNumberedItemContainer", limit = 1).find('input)

我已经通过打印出变量“nameBlock”来测试我找到了父函数,并且能够获取整个父 div 并在控制台中看到输入标签。但是当我尝试使用最后的“if”语句来查看是否能够找到输入元素时,我得到了这个错误:

AttributeError: ResultSet object has no attribute 'find_elements_by_tag_name'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()?

我认为它的父母也被选为该父母中的每个孩子,所以每个孩子都在寻找

nameBlock.find('input')

但我不确定我将如何选择子输入元素。有什么建议么?这里还有 HTML 可以更好地帮助理解我的问题。

【问题讨论】:

  • 你能添加你试图用BS解析的部分html代码吗
  • 这段html代码是由javascript动态创建的还是静态存在的? BS 将获取静态 html 代码,无法运行 javascript 生成其余页面

标签: python selenium web-scraping beautifulsoup webautomation


【解决方案1】:
AttributeError: ResultSet object has no attribute 'find_elements_by_tag_name'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()?

错误表明您使用了find_elements_by_tag_name(),它返回为list 而不是webelement

把这个改成

find_element_by_tag_name() 将作为 webelement 返回,您现在可以使用 send_keys() 方法。

【讨论】:

  • 我听从了你的建议,得到了同样的 AttributeError 错误:ResultSet object has no attribute 'find_element_by_tag_name'。您可能将元素列表视为单个元素。当您打算调用 find() 时,您是否调用了 find_all()?除了它说元素而不是元素,但你的建议合乎逻辑但不幸的是没有奏效
  • @DanielOcampo :如果可能,分享您的网址?
  • 您正在使用的网址并希望在输入字段中提供数据?
  • 我将如何再次这样做?
猜你喜欢
  • 1970-01-01
  • 2020-07-19
  • 1970-01-01
  • 1970-01-01
  • 2016-07-18
  • 1970-01-01
  • 2018-08-10
  • 2021-11-04
  • 1970-01-01
相关资源
最近更新 更多