【发布时间】:2017-01-18 12:39:11
【问题描述】:
我正在通过尝试解决问题来学习 python。
当我在登录站点后尝试访问某个元素时,相同的命令在 shell 中有效,如果它在以下文件中则无效。
另外,我认为我的方法是错误的,因为元素不断更改其 ID,唯一不变的是我尝试过的“更多搜索结果”:find_link_by_text 失败,我认为是因为元素不包含href。 find_link_by_xpath 和 contains 文本。
网页抓取:
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
import time
import requests, bs4, re, csv
chrome_path = r"C:\Users\-----\Desktop\chromedriver.exe"
driver = webdriver.Chrome(chrome_path)
driver.get("https://dir.indiamart.com/search.mp? ss=Power+Distribution+Transformers")
driver.maximize_window()
time.sleep(10) #setting a gap for website load
action = webdriver.ActionChains(driver)
elm = driver.find_element_by_id("user_sign_in").click()
inputElement = driver.find_element_by_id('email')
inputElement.send_keys('xxxxxx')
driver.find_element_by_name("Submit3").send_keys(Keys.RETURN)
time.sleep(30)
#The code till above this is working perfectly
# element:
#<div id="scroll2" class="fm2 p8 cur m_bt2"
#onclick="javascript:displayResultsLogin('scroll2')"> Show More Results
# </div>
try:
driver.find_element_by_id("scroll2").click()
#Trying the the above find_element_* works if I input it in shell.
except:
print("Didn't work")
pass
# If I leave it in the file, removing the except, it shows element not found
r = driver.page_source
soup = bs4.BeautifulSoup(r, 'html.parser')
blocks = soup.find_all('div', class_='lst')
with open('output.csv', 'w', newline='') as f:
writer = csv.writer(f)
for b in blocks:
name = b.find(class_='cnm').get_text(strip=True)
addr = b.find(class_='clg').get_text(strip=True)
call = b.find(class_='ls_co phn').find(text=re.compile('\d+')).strip()
writer.writerow([name, addr, call])
由于某种原因,在这个文件中的最后一部分,只会将元素中的 0 添加到文件中,而不是 xxxxxxxx 数字。
【问题讨论】:
-
更加清晰和简洁:您应该指定您正在尝试执行的操作、预期和实际输出的简短描述,只留下那些导致问题的代码行 + 添加异常日志(如果有)一个......目前还不清楚你在问什么
-
我确实发布了一个更中肯的问题,但似乎需要更多细节。我会编辑这个。
标签: python selenium web-scraping webdriver