所以基本上我正在做网络抓取/网站自动化,
这是我正在尝试做的一个简单示例:
我正在处理包含表单的动态页面,并且我想在此表单中插入数据。
当然,这个动态页面会根据我在此页面上发生之前插入的内容而变化。下面是我尝试在其中插入数据的 5 个不同页面的输入字段 ID 的示例。因此它是自动生成的,并且是唯一的:
- Listing.Item[国际象棋尺寸]
- Listing.Item[鞋子尺码]
- Listing.Item[尺码裤子]
- Listing.Item[尺寸]
- Listing.Item[鞋子尺码]
这里的字符串“Size”也是相同的模式。
我需要在此字段中插入数据,否则,我无法在表单上继续前进。这就是我尝试过的:
driver.find_element_by_id('Listing.Item[' + any(str) + 'Size' + any(str) + ']')
但是这不起作用。也许我错误地使用了函数“any()”。
How can automatically find this unique input in every page I come across, which always contains the string 'Size' in its ID ?
XPath 和 CSS 选择器还包含另一个单词(对于本例:Chess、Shoe 和 Trouser),因此我无法使用它们
感谢帮助
编辑:
这是完整的相应 HTML:
<input type="text" id="Listing.Item[Shoe Size]"
name="_st_Shoe Size" size="21" maxlength="50"
aria-required="true" value="">
=> name 和 id 的值每次都会改变
最佳答案
您可能想要尝试的是find_elements_by_css_selector
。该函数接受(顾名思义)CSS 选择器来返回元素。
CSS 选择器允许您搜索包含特定值的 ID。
例如,如果您要搜索 id 包含单词“Size”的所有输入标记,则可以使用:
css_selector = 'input[id*=Size]'
driver.find_elements_by_css_selector(css_selector)
*=
表示“包含”。
以下是一些您可能会觉得有用的资源:
关于python3/selenium/automation - 查找包含给定字符串的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43399353/