from selenium import webdriver from lxml import etree url = "https://appexchange.salesforce.com/appxStore" browser = webdriver.Chorme() browser.get(url) page_code = browser.page_source html_code = etree.HTML(page_code) # 将page_code 字符串解析成html app_names_xpath = '//*[@id="appx-table-results"]/li[*]/a/span[2]/span[2]/span[1]/span[2]/span[1]' app_names = html_code.xpath(app_names_xpath) # 这里返回的app_names 是一个列表, 里面存储着所有匹配的选项,如果没有的话列表就为空 print(app_names[0].text)
html_code = etree.parse("demo.html", etree.HTMLParser())
app_names_xpath = '//*[@id="appx-table-results"]/li[*]/a/span[2]/span[2]/span[1]/span[2]/span[1]' app_names = html_code.xpath(app_names_xpath) # 这里返回的app_names 是一个列表, 里面存储着所有匹配的选项,如果没有的话列表就为空 # text返回的是定位元素的文本内容 print(app_names[0].text)
定位有两种形式:
① 一种就是上面的定位元素,然后调用元素文本内容;
② 还有一种就是直接在定位元素的时候, 带上具体内容如:
# 第一种形式: app_names_xpath = '//*[@id="appx-table-results"]/li[*]/a/span[2]/span[2]/span[1]/span[2]/span[1]' app_names = html_code.xpath(app_names_xpath) print(app_names[0].text) 第二种形式: app_names_xpath = '//*[@id="appx-table-results"]/li[*]/a/span[2]/span[2]/span[1]/span[2]/span[1]/text()' app_names = html_code.xpath(app_names_xpath) print(app_names[0])
# 沿用上面的第二种形式:获取class属性的内容 ratings_path = '/html/body/div[1]/div[1]/div[1]/div/div/span[2]/div/ul/li[1]/a/span[1]/span[3]/span[2]/span[1]/span/span/@class' rating = html_code.xpath(ratings_path) print(rating[0])
选取对应的元素, 右键copy -》copy xpath