正则表达式地址查找
打印结果为空,大伙帮忙看看哪错了!import urllib.request
import re
def url_open(url):
req = urllib.request.Request(url)
req.add_header('User-Agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36')
response = urllib.request.urlopen(req)
html = response.read()
return html
def page_url(url):
html = url_open(url).decode('utf-8')
'''
<img width="236" height="354" class="lazy" alt="超大罩杯乳量快溢出!雪白"
src="https://img.youmzi.com/d/file/2020110709/rho2mv4uwbc.jpg"
'''
p = re.compile('<img width="\d{3}" height="\d{3}" class="\w*" alt="\S*" src="(http?:[//]+[\S]*.jpg)"')
img_list = p.findall(html)
for each in img_list:
print(each)
if __name__ == '__main__':
url = "https://www.youmzi.com/hot/"
page_url(url)
本帖最后由 suchocolate 于 2021-5-8 16:27 编辑
浏览器看到的和urllib get得到的html往往都不一样,这是因为浏览器会经过javascript渲染,而urllib不会。
你把response打印为文本,看一下就知道了,图片url不在src。
import urllib.request
import re
def main():
url = "https://www.youmzi.com/hot/"
req = urllib.request.Request(url)
req.add_header('User-Agent',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36')
r = urllib.request.urlopen(req)
html = r.read().decode('utf-8')
with open('result.html', 'w', encoding='utf-8') as f:# 去看看这个文件
f.write(html)
img_list = re.findall('data-original="(.*?)"', html)
for each in img_list:
print(each)
if __name__ == '__main__':
main()
suchocolate 发表于 2021-5-8 15:32
浏览器看到的和urllib get得到的html往往都不一样,这是因为浏览器会经过javascript渲染,而urllib不会。
...
原来如此,谢谢!{:5_109:}
页:
[1]