【问题标题】:How can I iterate through an excel sheet to perform a search on a webpage Python Selenium如何遍历 Excel 工作表以在网页上执行搜索 Python Selenium
【发布时间】:2019-08-15 09:32:41
【问题描述】:

我想遍历公司列表以逐一搜索并保存 href。

from selenium.webdriver import Firefox
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import pandas as pd
import pandas as pd
from lxml import html 
import time
import requests 
df=pd.read_excel('/Users/ap/companies.xlsx')
browser = Firefox(options=opts)
browser.get('https://webpage')
search_form=browser.find_element_by_id('ctl00_ContentPlaceHolder1_frmEntityName')
i=0
for i in df['company_name']:
    search_form.send_keys(i)
    search_form_buttom=browser.find_element_by_id('ctl00_ContentPlaceHolder1_btnSubmit').click()
#wait a bit to make this element work.search_form.send_keys('BioHealth')
    time.sleep(15)
    i=i+1 

我收到以下错误,我无法解决它,甚至无法抓取 hrefs。

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-68-e157420a273e> in <module>()
     21 #wait a bit to make this element work.search_form.send_keys('BioHealth')
     22     time.sleep(10)
---> 23     i=i+1
     24 

TypeError: coercing to Unicode: need string or buffer, int found 

【问题讨论】:

  • 在你的 for 循环中,你正在隐藏你在 for 循环之前拥有的整数 i。请将 for a 变量更改为更有意义的名称。好像是表示公司名称的字符串值
  • 但是如何在df['companies']列中依次遍历excel表中的所有公司,并用search_form.send_keys()一一搜索??跨度>
  • 但是如何在df['companies']列中依次遍历excel表中的所有公司,并用search_form.send_keys()一一搜索??跨度>
  • i = 0的目的是什么;在 for 循环之前,以及循环内的虚假 i = i+1 ?删除这两行,然后尝试。

标签: python selenium loops iteration


【解决方案1】:

for 循环将在df['company_name'] 中找到的字符串分配给它的变量i。在循环结束时,您将 1 添加到此字符串,这是不允许的,因为 python 解释器无法将 int 隐式转换为字符串。

我感觉您正在尝试使用 i=i+1 作为循环计数器变量,但在 for-each-loop(即 for i in foo)中不需要这样做。只需删除那个i=i+1。循环仍将按预期运行。

但是,如果你真的想给存储在i 中的字符串加一,你必须这样写: i=i+str(1) 然后python解释器会接受它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-25
    • 1970-01-01
    • 2020-08-28
    • 2020-04-05
    • 2020-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多