【发布时间】:2018-01-15 19:02:24
【问题描述】:
以下代码下载网页,查找和元素,然后运行正则表达式以解析字符串中的数字。它似乎适用于我的 python 3.7 测试系统,但不适用于我的 python 3.5。我正在下载一个网页,使用 Xpath 查找一个文本块。 xpath 返回类似“International (21)”或“Books (99)”之类的内容,我想提取数字,即 21 或 99。
在 python 3.5 中,我返回 'TypeError: '_sre.SRE_Match' object is not subscriptable。'
我不相信错误是版本的差异,但这是唯一已知的差异。 xpath 似乎正在工作,因为它返回 '<_sre.sre_match object span="(14," match="(21)">' 当我打印 CountObj 时。
我应该为 python 3.5 做一些调整吗,有没有更好的编码方法?
driver = webdriver.Chrome()
driver.get(url); #Download the URL passed from mysql
CatAndCount = driver.find_element_by_xpath('//h2 [@class="searchResultsTitle"]').text
# the above line returns with a name and value like 'International (21)'
CountObj = re.search("\((.*?)\)",CatAndCount) # look for the number, 21 in example
print (CountObj) # for testing
CountVal=CountObj[1]
【问题讨论】: