我正在从网站上抓取一些数据,有时它们会显示里程,有时它们会在车辆描述中显示 MPG这是网页
我正在使用 xpath,打算简单地按顺序进行
这是相关部分:
def init_driver():
options = webdriver.ChromeOptions()
options.binary_location = '/usr/bin/google-chrome-stable'
options.add_argument('headless')
options.add_argument('window-size=1200x600')
driver = webdriver.Chrome(chrome_options=options)
driver.wait = WebDriverWait(driver, 5)
return driver
def scrape(driver):
#Tymm = year make model All three attributes are in the Header, Parse and separate before insterting to SQL
ymm_element = driver.find_elements_by_xpath('//*[@id="compareForm"]/div/div/ul/li/div/div/h3')
engine_element = driver.find_elements_by_xpath('//*[@id="compareForm"]/div/div/ul/li/div/div/div[3]/dl[1]/dd[1]')
trans_element = driver.find_elements_by_xpath('//*[@id="compareForm"]/div/div/ul/li/div/div/div[3]/dl[1]/dd[2]')
milage_element = driver.find_elements_by_xpath('//*[@id="compareForm"]/div/div/ul/li/div/div/div[3]/dl[1]/dd[3]')
由于元素的顺序对于所有车辆都不相同,因此我需要编写它,以便它可以检索我想要的标题之后的文本。
以下是从元素检查中在 chrome 上复制 HTML 后的 HTML:
<div class="description">
<dl> <dt>Engine:</dt> <dd>2.5L I-5 cyl<span class="separator">,</span>
</dd> <dt>Transmission:</dt> <dd>Manual<span class="separator">,</span></dd> <dt>Mileage:</dt> <dd>37,171 miles<span class="separator">,</span></dd> <dt>MPG Range:</dt> <dd>22/31<span class="separator">,</span></dd></dl><dl class="last"> <dt>Exterior Color:</dt> <dd>Reflex Silver Metallic<span class="separator">,</span></dd> <dt>Interior Color:</dt> <dd>Titan Black<span class="separator">,</span></dd> <dt>Stock #:</dt> <dd>P3229</dd></dl> <span class="ddc-more">More<span class="hellip">…</span></span>
<div class="calloutDetails">
<ul class="list-unstyled">
<li class="certified" style="margin-bottom: 10px;"><div class="badge "><img class="align-center" src="https://static.dealer.com/v8/global/images/franchise/white/en_US/logo-certified-volkswagen.gif?r=1356028132000" alt="Certified"></div></li><li class="carfax" style="margin-bottom: 10px;"><a href="http://www.carfax.com/cfm/ccc_displayhistoryrpt.cfm?partner=DLR_3&vin=3VWHX7AT1EM600723" class="badge carfax-one-owner pointer" target="_blank"><img class="align-center" src="https://static.dealer.com/v8/global/images/franchise/white/logo-certified-carfax-one-owner-lrg.png?r=1405027620000" alt="Carfax One Owner"></a></li>
</ul>
</div>
<div class="hproductDynamicArea"></div>
</div>
基本上,我需要搜索标题后的文本,而不是对 xpath 进行编号。
我的年份和型号都在同一个元素中"标签,您能否指出正确的方向或建议图书馆分头
首先,使用 xpath,您可以使用包含,如下所示:
driver.find_elements_by_xpath('//dt[contains(text(),'Engine')]')
它看起来更干净,更易于使用且更坚固。
其次,阅读有关 xpath 跟随兄弟姐妹、前兄弟姐妹、父级和祖先的信息。它将帮助您构建整洁的 xpath 定位器:
driver.find_elements_by_xpath('//dt[contains(text(),'Engine:')]/following-sibling::dd')
driver.find_elements_by_xpath('//dt[contains(text(),'Transmission:')]/following-sibling::dd')
driver.find_elements_by_xpath('//dt[contains(text(),'Mileage:')]/following-sibling::dd')
上面的 xpath 将工作,无论您的 html 元素位于哪个顺序。