0

I have the following HTML page and I am using Selenium under python to extract some data from the page HTML

<span id="_ctl0_ContentPlaceHolder1_MyGrid__ctl2_ProductID2">050215-5g</span>

span id="_ctl0_ContentPlaceHolder1_MyGrid__ctl2_PriceBox2">$12.00</span>

I want to get the "050215-5g" and "$12.00" as text, and I used

pdt = div.find_elements_by_xpath('//*[contains(@id, "ProductID2")]')
price = div.find_element_by_xpath('//*[contains(@id, "PriceBox2")]')

When I print the 'pdt' and 'price', it returns

[<selenium.webdriver.remote.webelement.WebElement (session="da68ddac08948eab06fe7dedb51cbc85", element="8541d2ad-398c-4a04-baba-a982559da408")>, <selenium.webdriver.remote.webelement.WebElement (session="da68ddac08948eab06fe7dedb51cbc85", element="942ca30b-e779-48d0-91f7-23261aea67c5")>, <selenium.webdriver.remote.webelement.WebElement (session="da68ddac08948eab06fe7dedb51cbc85", element="81bd8036-17d0-4aba-a8a1-454842396d9a")>, <selenium.webdriver.remote.webelement.WebElement (session="da68ddac08948eab06fe7dedb51cbc85", element="ecf3064a-bae2-46b1-85a5-d111bbd8f7f6")>]|<selenium.webdriver.remote.webelement.WebElement (session="da68ddac08948eab06fe7dedb51cbc85", element="8541d2ad-398c-4a04-baba-a982559da408")>|<selenium.webdriver.remote.webelement.WebElement (session="da68ddac08948eab06fe7dedb51cbc85", element="95e82bff-f7c9-40c4-aee4-4e95e850c6f1")>

I also tried

pdt = div.find_elements_by_xpath('//*[contains(@id, "ProductID2")]').text
price = div.find_element_by_xpath('//*[contains(@id, "PriceBox2")]').text

it gives me "AttributeError: 'list' object has no attribute 'text'"

Can anyone help me to solve this problem? Thanks!

1 Answers1

1

Whatever your element is, is a list. The error is clear. Even if the list is 1 element, you need to print the first element. i.e.,

print(elements[0].text)
#              ^ Grab the first element

In example:

elements = div.find_element_by_xpath('//*[contains(@id, "PriceBox2")]')
print(elements[0].text)
simbleau
  • 76
  • 1
  • 4
  • Thanks for your reply. When I run the code, it replies 'WebElement' object does not support indexing.Do you have any idea how can I resolve it? – Yuchen Ding Jan 01 '21 at 19:39
  • Check https://stackoverflow.com/questions/28022764/python-and-how-to-get-text-from-selenium-element-webelement-object – simbleau Jan 02 '21 at 01:58