首页 > 解决方案 > Python Selenium 如何在一个代码中与两种不同的网站格式进行交互

问题描述

我正在交互的网站上有两种格式:

还有两种链接格式:(标题在 a[1] 或 a[2]

<div class="company-left-title">
            <a href="http://hubeianran.58food.com/" target="_blank">湖北安然保健品有限公司&lt;/a>
                <p><a href="/company_hubeianran.html" target="_blank">[企业黄页]</a></p>
                
            </div>

或者

<div class="company-left-title">
<a href="javascript:Go('/qy-l-0-4-3595-3595-1.html');">
            </a><a href="http://15256160037.58food.com/" target="_blank">亳州市九熹堂药业有限公司</a>  
            </div>

我正在尝试获取这些网站上的联系信息、网站并将它们放入 csv 中。在第二种格式中,我必须单击另一个按钮才能获取整个信息

我用了:

driver.get('http://www.58food.com/qy-l-0-3595.html')
while True:
  try:
     links = [link.get_attribute('href') for link in driver.find_elements_by_xpath('//*[@class="company-left-title"]/a[2]')]
  except:
     links = [link.get_attribute('href') for link in driver.find_elements_by_xpath('//*[@class="company-left-title"]/a[1]')]
  locs = [loc.text for loc in driver.find_elements_by_xpath('//*[@class="company-text"]/p')]
    for link,loc in zip(links,locs):
        time.sleep(2)
        driver.get(link)
        windows = driver.window_handles
        driver.switch_to.window(windows[-1])
        driver.find_element_by_link_text('联系方式').click()
        try:
          company = driver.find_element_by_xpath('//*[@class="rclefttop"]/strong').text
          con_num = driver.find_element_by_xpath('//*[@class="rcleftlist"]/i[1]').text
          driver.back()
          driver.back()
        except:
          company = driver.find_element_by_xpath('//*[@class="px14 lh18"]/table/tbody/tr[1]/td[2]').text
          driver.find_element_by_id('glo_contactway_content').click()
          con_num = driver.find_element_by_xpath('//*[@class="archives dr-archives relative"]/p[1]').text
          driver.find_element_by_id('close').click()
          website = driver.find_element_by_xpath('//*[@class="px14 lh18"]/table/tbody/tr[5]/td[2]/a').text
          driver.back()
          driver.back()
        dataframe = pd.DataFrame({'col1':company,'col2':con_num,'col3':con_num2,'col4':loc,'col5':website},index=[0])

    try:
        next_page = driver.find_element_by_link_text("下一页&quot;)
        next_page.click()
    except:
          print('No more pages')
          break

ElementNotInteractableException:元素不可交互(会话信息:chrome=88.0.4324.104)

有人可以帮忙解决这个问题吗?

标签: pythonselenium

解决方案


可能是您尝试单击的对象仍在加载,这就是为什么无法单击的原因。尝试显式等待,直到您尝试单击的对象可见且可单击。有关更多信息,请参阅链接。


推荐阅读