【问题标题】:How do I find a link object with a specific id-tag using mechanize?如何使用 mechanize 找到具有特定 id-tag 的链接对象?
【发布时间】:2019-08-31 21:11:33
【问题描述】:

我正在编写一个网页抓取脚本,在某些时候应该点击带有特定 id-tag 的锚链接。我可以使用 BeautifulSoup 找到链接,但是我找不到使用 mechanize 获取 mechanize.Link 对象的方法。

这是我目前的代码。

import mechanize

br = mechanize.Browser()
response = br.open("myUrl")

for link in br.links():
    if str(link.attrs["id"]) == "cell_14_2":
        click_link(link)
    break

我希望找到 ID 为“cell_14_2”的链接对象,但我收到一条错误消息:

if str(link.attrs["id"]) == "cell_14_2":

消息是:

TypeError: list indices must be integers, not str

如何找到 mechanize.Link 对象并单击它?

【问题讨论】:

    标签: python html hyperlink mechanize


    【解决方案1】:

    链接对象上的属性被保存为(名称,值)对的序列。所以你应该先创建一个字典,然后再通过 id 查询一个项目。例如:

    for link in br.links():
        attrs = dict(link.attrs)  # First create a dict
        if str(attrs["id"]) == "cell_14_2":  # Now you can ask for the `id`
    

    【讨论】:

      猜你喜欢
      • 2015-03-24
      • 2021-01-28
      • 1970-01-01
      • 2012-10-20
      • 1970-01-01
      • 2011-05-03
      • 1970-01-01
      • 2017-07-07
      • 1970-01-01
      相关资源
      最近更新 更多