无法打印href?

问题描述 投票:0回答:2

我一直在搜索整个网站,希望找到答案,但是,我查看的每个问题都没有像我试图抓取的页面那样严重嵌套的HTML代码。我真的希望有人会发现我明显的错误。我有以下代码,它提取类别标题,但令人讨厌的不是与每个标题一起使用的href。运行时,代码当前为所有href返回'None',但我无法解释原因。我认为这可能是因为我在HTML中定位了错误的元素,标记或类,但无法正确识别它应该是哪一个。

from selenium import webdriver
import time

# The website to scrape
url = "https://www.jtinsight.com/JTIRA/JTIRA.aspx#!/full-category-list"

# Creating the WebDriver object using the ChromeDriver
driver = webdriver.Chrome()

# Directing the driver to the defined url
driver.get(url)

# driver.implicitly_wait(5)
time.sleep(1)

# Locate the categories
categories = driver.find_elements_by_xpath('//div[@class="subCatEntry ng-scope"]')

# Print out all categories on current page
num_page_items = len(categories)
print(num_page_items)
for headers in range(num_page_items):
    print(categories[headers].text)
for elem in categories:
    print(elem.get_attribute("a.divLink[href='*']"))

# Clean up (close browser once task is completed)
time.sleep(1)
driver.close()

如果有人能指出我的错误,我真的很感激。

python python-3.x selenium selenium-webdriver
2个回答
1
投票

请尝试以下代码。

for elem in categories:
    print(elem.find_element_by_css_selector("a.divLink").get_attribute('href'))

0
投票

您正在传递get_attribute方法的CSS选择器。那不行。您只需提供属性名称。如果web元素elem具有名为href的属性,那么它将打印该属性的值。

首先,获取锚<a>元素。所有子类别锚点都有类divLink。为获得锚元素试试这个,

categories = driver.find_elements_by_class_name('divLink')

其次,通过在get_ttribute中传递属性名称来打印属性值。试试这个,

print(elem.get_attribute("href"))

这样您就可以打印所有href值。

© www.soinside.com 2019 - 2024. All rights reserved.