【问题标题】:http request and regex in Python for HTML parserPython中用于HTML解析器的http请求和正则表达式
【发布时间】:2016-08-04 17:51:10
【问题描述】:

当我执行脚本时,结果为空。为什么?该脚本与站点连接并解析html标签<a>

#!/usr/bin/python3

import re
import socket
import urllib, urllib.error
import http.client
import sys

conn = http.client.HTTPConnection('www.guardaserie.online');
headers = { "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
                "Content-type": "application/x-www-form-urlencoded; charset=UTF-8" }
params = urllib.parse.urlencode({"s":"hannibal"})
conn.request('GET', '/',params, headers)
response = conn.getresponse();

site = re.search('<a href="(.*)" class="box-link-serie">', str(response.read()), re.M|re.I)
if(site):
  print(site.group())

【问题讨论】:

标签: python get http.client


【解决方案1】:

您正在搜索的模式很可能在读取响应中不存在,或者在尝试解析 html 时出现阻塞。

re.search( 'href="(.*)" class="box-link-serie"', str(response.read()), re.M | re.I )

使用更通用的方法或其他解析器方法可能会导致您获得所需的结果。

【讨论】:

  • 如果你尝试了上面的模式,它应该会返回一个结果。我建议您尝试使用这些导入:import re, httplib, socket, urllib, sys,并更改params = urllib.urlencode,以及conn = httplib.HTTPConnection ...
  • 模式返回整个html页面
  • 结果总是这样
  • 我在使用print(site.group())时得到href="http://www.guardaserie.online/ray-donovan-a/" class="box-link-serie" ...这里的python代码:gist.github.com/anonymous/43026f7262b2fddfb7643169f0d558b2
猜你喜欢
  • 1970-01-01
  • 2010-09-08
  • 1970-01-01
  • 2012-09-12
  • 2016-09-23
  • 2014-06-26
  • 1970-01-01
  • 2020-03-14
  • 2012-06-05
相关资源
最近更新 更多