Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python regex和urllib.request从HTML中刮取链接_Python_Regex_Html Parsing_Urllib - Fatal编程技术网

Python regex和urllib.request从HTML中刮取链接

Python regex和urllib.request从HTML中刮取链接,python,regex,html-parsing,urllib,Python,Regex,Html Parsing,Urllib,我试图解析HTML以提取此正则表达式构造中的所有值: href=“http/。+?” 代码如下: import urllib.request import re url = input('Enter - ') html = urllib.request.urlopen(url).read() links = re.findall('href="(http://.*?)"',html) for link in links: print(link) 但我得到了一个错误

我试图解析HTML以提取此正则表达式构造中的所有值: href=“http/。+?”

代码如下:

import urllib.request
import re

url = input('Enter - ')
html = urllib.request.urlopen(url).read()
links = re.findall('href="(http://.*?)"',html)
for link in links:
    print(link)
但我得到了一个错误,说:
TypeError:无法在类似字节的对象上使用字符串模式

您的
html
是字节字符串,请使用
str(html)

或者,使用字节模式:

re.findall(rb'href="(http://.*?)"',html)

您的
html
是一个字节字符串,请使用
str(html)

或者,使用字节模式:

re.findall(rb'href="(http://.*?)"',html)
urlopen(url)
返回字节对象。因此,您的
html
变量也包含字节。您可以使用如下方式对其进行解码:

htmlobject = urllib.request.urlopen(url)
html = htmlobject.read().decode('utf-8')
然后可以在正则表达式中使用现在是字符串的
html

urlopen(url)
返回字节对象。因此,您的
html
变量也包含字节。您可以使用如下方式对其进行解码:

htmlobject = urllib.request.urlopen(url)
html = htmlobject.read().decode('utf-8')

然后你可以在你的正则表达式中使用
html
,它现在是一个字符串。

如果你想要一个页面上的所有链接,你甚至不需要使用正则表达式。因为您只需使用bs4即可获得所需内容:-)


希望能有所帮助。祝项目顺利;-)

如果你想要一个页面上的所有链接,你甚至不需要使用正则表达式。因为您只需使用bs4即可获得所需内容:-)


希望能有所帮助。祝项目顺利;-)

谢谢你,妈妈。我以后再做。我刚刚开始学习python中的正则表达式来进行解析。bs4将是下一章。谢谢你@妈妈。我以后再做。我刚刚开始学习python中的正则表达式来进行解析。bs4将是下一章。@TaufiqueRahman很高兴听到这个消息,请单击左侧的灰色记号。@TaufiqueRahman很高兴听到这个消息,请单击左侧的灰色记号。