爬虫整理(一)使用re和urllib

本页代码

from urllib.request import urlopen


html = urlopen(
    "https://morvanzhou.github.io/static/scraping/basic-structure.html").read(
        
    ).decode('utf-8')
print(html)


import re
res = re.findall(r"<title>(.+?)</title>", html)
print("\nPage title is: ", res[0])


res = re.findall(r"<p>(.*?)</p>", html, flags=re.DOTALL) 
print("\nPage paragraph is: ", res[0])


res = re.findall(r'href="(.*?)"', html)
print("\nAll links: ", res)

正文

使用re和urllib

from urllib.request import urlopen
# if has Chinese, apply decode()
html = urlopen(
    "https://morvanzhou.github.io/static/scraping/basic-structure.html"
).read().decode('utf-8')  
print(html) # 打开,读取,转换可显示中文,最后打印出来

结果显示

print(html)

接下来,使用re筛选数据

import re
res = re.findall(r"<title>(.+?)</title>", html) 
print(res)  # ['Scraping tutorial 1 | 莫烦Python'] # 列表
print(res[0]) # Scraping tutorial 1 | 莫烦Python
res = re.findall(r"<p>(.*?)</p>", html)
print(res)  # []

res = re.findall(r"<p>(.*?)</p>", html, flags=re.DOTALL) 
# re.DOTALL if multi line
prnt(res)
print(res[0]) 
以上五个的print数据
res = re.findall(r'href="(.*?)"', html)
print("\nAll links: ", res)
筛选链接
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容