硒的问题,尤其是优化问题



伙计们,我的代码效率有问题

我需要从带有土地属性/公寓的网页中提取某些数据,然后再进行分析,但我的代码运行速度非常慢,你能帮我吗?

PS我是一个新的网页刮

driver.get('https://www.olx.pl/nieruchomosci/dzialki')

innerLayout = driver.find_element_by_id('innerLayout')
print(innerLayout)
container = innerLayout.find_element_by_id('body-container')
offer_wrap = container.find_elements_by_class_name("offer-wrapper")
for i in offer_wrap:
link = driver.find_element_by_xpath('//*[@id="body-container"]/div[3]/div/div[1]/table[1]/tbody/tr[3]/td/div/table/tbody/tr[1]/td[2]/div/h3/a')
link.click()
outerClass = driver.find_element_by_id('offerdescription')
time.sleep(10)
#price of field
parcel = outerClass.find_elements_by_xpath('//*[@id="offerdescription"]/div[2]/ul/li[3]/span/strong')
price= []
for i in parcel:
price.append(i.text)
time.sleep(10)
#surface
surface = outerClass.find_elements_by_xpath('//*[@id="offerdescription"]/div[2]/ul/li[4]/span/strong')
surf = []
for j in surface:
surf.append(j.text)
time.sleep(10)
driver.back()


print(price)
print(surf)

请避免time.sleep()。这是一种静态等待,即使元素可见并且可以进行交互,它仍然会等待。

根据你的代码,我找不到更好的情况,比如你为什么在某个时候使用10秒睡眠。

这是一个例子,你可以用显式等待代替你的时间。睡眠:

element = WebDriverWait(driver, 5).until(
EC.presence_of_element_located((By.XPATH, "Your element Xpath here"))
)

此外,您的大多数xpath都是绝对的,请使用相对xpath,这将使您的脚本更加稳定。

我这里有一些好的xpath给你:

Your xpath : //*[@id="body-container"]/div[3]/div/div[1]/table[1]/tbody/tr[3]/td/div/table/tbody/tr[1]/td[2]/div/h3/a
Better xpath : (//table[@summary='Ogłoszenie']//tr//td//h3/a)[1]

Your xpath : //*[@id="offerdescription"]/div[2]/ul/li[3]/span/strong
Better xpath : (//span[@class='offer-details__name'])[3]

Your xpath : //*[@id="offerdescription"]/div[2]/ul/li[4]/span/strong
Better xpath : (//span[contains(@class,'name')])[4]

请记住,xpath的优化可能不会对脚本的执行速度产生太大影响,但它肯定会使脚本稳定。

我理解你对time.sleep()的使用,但你最好避免它。试着使用WebDriverWait。你可以在这里找到

最新更新