Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Selenium(PYTHON)获取href的特定属性_Python_Selenium_Webautomation - Fatal编程技术网

Selenium(PYTHON)获取href的特定属性

Selenium(PYTHON)获取href的特定属性,python,selenium,webautomation,Python,Selenium,Webautomation,因此,我有这个href元素,我试图只打印href中的数字,但是元素后面的href路径也包含数字,因此我不确定如何准确地只获取数字,而不是同时在Mad1000中打印数字 hrefhttps://www.game.com/items/20573078/Mad1000 userLink = driver.find_element_by_xpath(f"//*[@id='bc_owners_table']/tbody/tr[{i+1}]/td[7]/a").get_attribute

因此,我有这个href元素,我试图只打印href中的数字,但是元素后面的href路径也包含数字,因此我不确定如何准确地只获取数字,而不是同时在Mad1000中打印数字

href
https://www.game.com/items/20573078/Mad1000

userLink = driver.find_element_by_xpath(f"//*[@id='bc_owners_table']/tbody/tr[{i+1}]/td[7]/a").get_attribute("href")


userID = re.sub('[^0-9]', '', userLink)
print(userID)

结果是205730781000,但我正在尝试导航到只能打印20573078的位置,我如何实现这一点呢

userID=[href.split(“/”)中s的int(s)如果s.isdigit()]
打印(用户标识[0])
userID=re.findall(r'\d+',href)
打印(用户标识[0])
userID=href.split(“/”[4]
打印(用户ID)
userID=re.sub(“[^0-9]”,“”,href)[:-4]
打印(用户ID)
让我解释一下。PS:我使用了
href
变量,但您可以将其更改为
userLink
,它应该可以工作

第一种方法每次出现
/
时都将字符串拆分为一个列表。然后检查列表中每个项目的值是否为整数。这是作为列表返回的,因此我们使用
userID[0]
获取列表中的第一个(通常是唯一的!)元素。Mad1000不在列表中的原因是它由字符串和整数组成。列表将只包含整数

第二个方法返回字符串中每个数字的列表作为列表。因此,这次将添加
1000
,因为它是一个数字,因此,我们使用
userID[0]
获取列表的第一个元素,它将是
20573078
,因为前面没有任何数字(但是如果href更改,可能会有)

第三种方法通过
/
再次将字符串拆分为一个列表。不同的是,这一次,我们直接得到列表中的第四个元素。您可能需要到处玩,因为根据超链接的不同,您可能需要访问第3或第5个元素。这是选项1的替代方案,选项1与此类似,但也会检查值是否为数字

最后1使用您的方法获取数字,但使用
[:-4]
删除最后4个值


这些方法都不是十全十美的,但它们应该能满足您的需要。

好的,第一种方法似乎是我在这种情况下最有效的方法,以防数字发生变化,谢谢,这很有用没有问题!我很高兴这有帮助!