是否有可能将更强大的HTML解析器连接到Python机械化?

int*_*nt3 9 python mechanize

我试图使用mechanize在网站上解析并提交表单,但看起来内置表单解析器无法检测表单及其元素.我怀疑它在形成不良的HTML上很窒息,我想尝试使用一个解析器进行预解析,该解析器更好地设计用于处理错误的HTML(例如lxml或BeautifulSoup),然后将经过修饰的清理输出提供给表单解析器.我需要机械化不仅用于提交表单而且用于维护会话(我在登录会话中使用此表单.)

我不确定如何做到这一点,如果它确实可能..我不熟悉HTTP协议的各种细节,如何让各个部分一起工作等等.任何指针?

cer*_*ros 10

我有一个问题,表单字段中缺少表单字段,我找不到任何格式错误的HTML,但我认为这是原因所以我使用BeautifulSoup的美化功能来解析它,它工作.

resp = br.open(url)
soup = BeautifulSoup(resp.get_data())
resp.set_data(soup.prettify())
br.set_response(resp)
Run Code Online (Sandbox Code Playgroud)

我很乐意自动知道如何做到这一点.

编辑:了解如何自动执行此操作

class PrettifyHandler(mechanize.BaseHandler):
    def http_response(self, request, response):
        if not hasattr(response, "seek"):
            response = mechanize.response_seek_wrapper(response)
        # only use BeautifulSoup if response is html
        if response.info().dict.has_key('content-type') and ('html' in response.info().dict['content-type']):
            soup = BeautifulSoup(response.get_data())
            response.set_data(soup.prettify())
        return response

    # also parse https in the same way
    https_response = http_response

br = mechanize.Browser()
br.add_handler(PrettifyHandler())
Run Code Online (Sandbox Code Playgroud)

br现在将BeautifulSoup用于解析内容类型(mime类型)中包含html的所有响应,例如text/html


Adr*_*son 3

阅读机械化网站首页上的大示例:

# Sometimes it's useful to process bad headers or bad HTML:
response = br.response()  # this is a copy of response
headers = response.info()  # currently, this is a mimetools.Message
headers["Content-type"] = "text/html; charset=utf-8"
response.set_data(response.get_data().replace("<!---", "<!--"))
br.set_response(response)
Run Code Online (Sandbox Code Playgroud)

因此,似乎很有可能使用另一个解析器来预处理响应,该解析器将重新生成格式良好的 HTML,然后将其反馈给 mechanize 进行进一步处理。