python - 如何使用 html.parser
问题描述
大家好,我是 python 的新手,正在尝试使用 python 的 html.parser 模块,我想抓取这个网站并使用li
标签
https://www.mcdelivery 中的 html.parser获取网址、交易名称和价格.com.pk/pk/browse/menu.html
获取 url 后,我想将它们附加到基本 URL 中,并从该站点获取价格交易。
import urllib.request
import urllib.parse
import re
from html.parser import HTMLParser
url = 'https://www.mcdelivery.com.pk/pk/browse/menu.html'
values = {'daypartId': '1', 'catId': '1'}
data = urllib.parse.urlencode(values)
data = data.encode('utf-8') # data should be bytes
req = urllib.request.Request(url, data)
resp = urllib.request.urlopen(req)
respData = resp.read()
list1 = re.findall(r'<div class="product-cost"(.*?)</div>', str(respData))
for eachp in list1:
print(eachp)
正在使用正则表达式来抢课,但我失败了。现在试图弄清楚如何使用 html.parser 来做到这一点。我知道这项工作会变得更容易,beautifulsoup and scrapy
但我正在尝试使用裸 python,所以请跳过第 3 方库。我真的需要帮助。我被困住了。Html.parser 代码(更新)
from html.parser import HTMLParser
import urllib.request
import html.parser
# Import HTML from a URL
url = urllib.request.urlopen(
"https://www.mcdelivery.com.pk/pk/browse/menu.html")
html = url.read().decode()
url.close()
class MyParser(html.parser.HTMLParser):
def __init__(self, html):
self.matches = []
self.match_count = 0
super().__init__()
def handle_data(self, data):
self.matches.append(data)
self.match_count += 1
def handle_starttag(self, tag, attrs):
attrs = dict(attrs)
if tag == "div":
if attrs.get("product-cost"):
self.handle_data()
else:
return
parser = MyParser(html)
parser.feed(html)
for item in parser.matches:
print(item)
解决方案
这是一个可能需要特定调整的良好开端:
import html.parser
class MyParser(html.parser.HTMLParser):
def __init__(self, html):
self.matches = []
self.match_count = 0
super().__init__()
def handle_data(self, data):
self.matches.append(data)
self.match_count += 1
def handle_starttag(self, tag, attrs):
attrs = dict(attrs)
if tag == "div":
if attrs.get("product-cost"):
self.handle_data()
else: return
用法大致如下
request_html = the_request_method(url, ...)
parser = MyParser()
parser.feed(request_html)
for item in parser.matches:
print(item)
推荐阅读
- python - 尝试在 Django 中进行特定分组
- angular - Angular 9 - 日期选择器显示错误的日期
- image - Base64:无效长度必须是四的倍数:颤动中的错误
- java - Java中有多少个Futures太多了?
- javascript - js 'click' 功能/EventListener 问题
- c# - C#:如何在更改另一个下拉列表时更改下拉列表的内容?
- azure - Azure PostgreSQL 是否支持自定义证书而不是用户名和密码?
- arrays - Typescript:字符串联合和具有相同项目类型的完整数组的DRY定义
- sql-server - 如何找到分布在 SQL Server 中多行的数据的第一个和最后一个数据点
- javascript - bootstrap 4的轮播的实现不起作用