8

私はSeleniunWebDriverとPythonにかなり慣れていないので、私の質問は基本的なものかもしれません。

したがって、次のHTMLコードがあります。

<a class="wp-first-item" href="admin.php?page=account">Account</a>

そして、XPathがであることを知って、XPathを使用してhrefを抽出しようとしてい".//*[@id='toplevel_page_menu']/ul/li[2]/a"ます。

それ、どうやったら出来るの?

driver.find_element_by_xpath(".//*[@id='toplevel_page_menu']/ul/li[2]/a").link

また

driver.find_element_by_xpath(".//*[@id='toplevel_page_menu']/ul/li[2]/a").href

動作しないようで、次の結果になります。

AttributeError: 'WebElement' object has no attribute 'link'

結果は次のようになると思い"admin.php?page=account"ます。

4

1 に答える 1

15

あなたが使用することができますget_attribute

element = driver.find_element_by_xpath(".//*[@id='toplevel_page_menu']/ul/li[2]/a")
href = element.get_attribute('href')
print href

通常、私はSeleniumを使用してページに移動し、ソースを取得して、BeautifulSoupで解析します。

from BeautifulSoup import BeautifulSoup

# On the current page
source = driver.page_source
soup = BeautifulSoup(source)

href = soup('<the tag containing the anchor>',{'id':'toplevel_page_menu'})[0]('ul')[0]('li')[2]('a')[0]['href']

残念ながら、BeautifulSoupはxpathをサポートしていないため、上記はxpathのBS表現です(私が理解している限り)。

于 2013-03-13T14:51:32.383 に答える