h5-attribute和property

本文介绍了HTML5中的attribute和property的概念,包括attribute是HTML自定义或预定义属性,而property是JavaScript中对象的直接属性。每个预定义的attribute都有对应的property。接着讨论了布尔值属性和非布尔值属性的差异,以及attribute与property的同步关系,特别是用户操作实际上是在操作property。最后,建议在jQuery中,对于布尔值属性使用prop方法,而非布尔值属性则使用attr方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.什么是attribute,什么是property属性?
attribute: html自定义属性 和预定义属性
property: js原生对象的直接属性
每一个预定义的attribute都会有一个property与之对应
2.什么是布尔值属性,什么是非布尔值属性?
property所对应的值是否为布尔值类型
3.attribute和property同步关系
非布尔值属性: 实时同步
布尔值属性:
没有动过property,attribute会同步property,property不会同步attribute
动过property,都不会同步
4.用户操作的是property
浏览器认property
5.Jquery中两个方法attr() prop()
布尔值属性最好使用prop方法
非布尔值属性attr方法

<input type="checkbox" checked="checked" name="lyp"  />  <!--checked既是input标签的attribute(对于html),又是input节点的property(对于js)-->
	     <script type="text/javascript">
			 
	     	var l= document.querySelector("input[type=checkbox]")
			//布尔值属性:你的property是布尔值类型   checked就是布尔值属性  改变property不会同步attribute
			debugger
			l.setAttribute("checked","checked1") //操作标签的attribute
			l.setAttribute("checked","checked2")
			
			l.checked = true
			l.checked = "checked3"  //操作节点的property
			l.checked = "checked4"
				
			debugger
			//非布尔值属性:你的property是非布尔值类型  name就是非布尔值属性 在非布尔值属性里面,property和attribute会实时同步
			l.setAttribute("name",'lalala')
			
			l.name = "heheh"
			
			//浏览器只认property
			
	     </script>

在这里插入图片描述

-- coding: utf-8 -- import requests import json import csv import random import re from datetime import datetime import time class TM_producs(object): def init(self, storename): self.storename = storename self.url = ‘https://{}.m.tmall.com’.format(storename) self.headers = { “user-agent”: "Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 " “(KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1” } datenum = datetime.now().strftime(‘%Y%m%d%H%M’) self.filename = ‘{}_{}.csv’.format(self.storename, datenum) self.get_file() def get_file(self): '''创建一个含有标题的表格''' title = ['item_id', 'price', 'quantity', 'sold', 'title', 'totalSoldQuantity', 'url', 'img'] with open(self.filename, 'w', newline='') as f: writer = csv.DictWriter(f, fieldnames=title) writer.writeheader() return def get_totalpage(self): '''提取总页码数''' num = random.randint(83739921, 87739530) endurl = '/shop/shop_auction_search.do?sort=s&p=1&page_size=12&from=h5&ajson=1&_tm_source=tmallsearch&callback=jsonp_{}' url = self.url + endurl.format(num) html = requests.get(url, headers=self.headers).text infos = re.findall('\(({.*})\)', html)[0] infos = json.loads(infos) totalpage = infos.get('total_page') return int(totalpage) def get_products(self, page): '''提取单页商品列表''' num = random.randint(83739921, 87739530) endurl = '/shop/shop_auction_search.do?sort=s&p={}&page_size=12&from=h5&ajson=1&_tm_source=tmallsearch&callback=jsonp_{}' url = self.url + endurl.format(page, num) html = requests.get(url, headers=self.headers).text infos = re.findall('\(({.*})\)', html)[0] infos = json.loads(infos) products = infos.get('items') title = ['item_id', 'price', 'quantity', 'sold', 'title', 'totalSoldQuantity', 'url', 'img'] with open(self.filename, 'a', newline='') as f: writer = csv.DictWriter(f, fieldnames=title) writer.writerows(products) def main(self): '''循环爬取所有页面宝贝''' total_page = self.get_totalpage() for i in range(1, total_page + 1): self.get_products(i) print('总计{}页商品,已经提取第{}页'.format(total_page, i)) time.sleep(1 + random.random()) if name == ‘main’: storename = ‘uniqlo’ tm = TM_producs(storename) tm.main() C:\Users\ESD\AppData\Local\Programs\Python\Python311\python.exe C:/Users/ESD/Desktop/文件夹集合/python/BigData/爬虫/test.py Traceback (most recent call last): File “C:\Users\ESD\Desktop\文件夹集合\python\BigData\爬虫\test.py”, line 68, in <module> tm.main() File “C:\Users\ESD\Desktop\文件夹集合\python\BigData\爬虫\test.py”, line 58, in main total_page = self.get_totalpage() ^^^^^^^^^^^^^^^^^^^^ File “C:\Users\ESD\Desktop\文件夹集合\python\BigData\爬虫\test.py”, line 38, in get_totalpage infos = json.loads(infos) ^^^^^^^^^^^^^^^^^ File “C:\Users\ESD\AppData\Local\Programs\Python\Python311\Lib\json_init_.py”, line 346, in loads return _default_decoder.decode(s) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File “C:\Users\ESD\AppData\Local\Programs\Python\Python311\Lib\json\decoder.py”, line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File “C:\Users\ESD\AppData\Local\Programs\Python\Python311\Lib\json\decoder.py”, line 353, in raw_decode obj, end = self.scan_once(s, idx) ^^^^^^^^^^^^^^^^^^^^^^ json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1) 进程已结束,退出代码1 修正问题并给出完整代码
最新发布
03-11
<think>好的,我现在需要帮助用户解决他们提供的Python代码中的错误。用户遇到的错误是JSONDecodeError,提示在解析JSON时出现问题,具体是期望属性名被双引号包裹。首先,我需要仔细分析用户提供的代码错误信息,找出可能的原因。 首先,用户提供的代码是一个爬虫,用于从淘宝移动端页面抓取商品信息。代码中使用了requests库发送HTTP请求,然后通过正则表达式提取响应中的JSON数据,再使用json.loads解析。错误发生在json.loads(infos)这一行,说明infos变量中的内容不是有效的JSON格式。 接下来,我需要查看用户是如何提取JSON数据的。在get_totalpage方法中,用户使用正则表达式re.findall('\(({.*})\)', html)[0],这里试图匹配括号内的内容。可能的问题在于正则表达式不够精确,导致提取的字符串不是有效的JSON。例如,如果响应中有多个括号或者结构复杂,正则表达式可能无法正确捕获完整的JSON数据,导致解析失败。 另外,JSON的标准要求键名字符串值必须使用双引号,而用户返回的数据可能使用了单引号或者没有正确转义某些字符,导致json模块无法解析。例如,如果服务器返回的JSON中有未转义的特殊字符,或者键名用了单引号,都会引发这个错误。 接下来,我需要检查代码中的细节。注意到用户代码中在初始化URL时使用了错误的引号,比如‘https://{}.m.tmall.com’‘main’中的引号,这些应该是单引号或双引号,但用户可能误用了中文引号或其它符号。这可能导致语法错误,但用户提供的错误信息显示问题出在JSON解析阶段,所以可能这部分在用户实际代码中已经修正,或者在粘贴到问题时格式有误。 另外,在get_products方法中,用户同样使用了相同的正则表达式来提取JSON数据,同样可能存在提取不准确的问题。此外,随机数的生成范围是否合理,以及请求头是否正确设置,也可能影响服务器返回的数据格式。 解决方案方面,首先需要修正正则表达式,确保正确提取JSON字符串。可能需要调整正则表达式,例如使用非贪婪匹配,或者更精确的模式。其次,处理JSON解析前,可以打印或记录infos变量,确认其内容是否为有效的JSON。如果服务器返回的数据包含JSONP回调函数,如jsonp_123456(...),则正则表达式需要准确提取括号内的内容。 另外,处理可能存在的字符转义问题,例如在JSON字符串中是否存在未转义的反斜杠或引号。可能需要在解析前对字符串进行清理,比如替换单引号为双引号,或者处理Unicode字符。 最后,代码中的一些语法问题,如类的方法定义缺少self参数,init方法应为__init__,这些可能是在用户粘贴代码时产生的格式错误,需要修正以确保代码能正常运行。 总结可能的问题点: 1. 正则表达式提取JSON数据不准确,导致infos包含无效字符。 2. JSON字符串中的键名使用了单引号而非双引号。 3. 服务器返回的数据包含其他字符或结构,导致JSON解析失败。 4. 代码中存在语法错误,如引号使用不当、方法命名错误等。 修正步骤: 1. 修正正则表达式,使用更精确的匹配模式,如re.search(r'\({(.*?)}\)', html, re.DOTALL),确保提取完整的JSON内容。 2. 在解析前打印或检查infos的内容,确认其有效性。 3. 处理可能的JSON格式问题,如替换单引号为双引号,或使用json.JSONDecoder的strict参数忽略某些错误。 4. 修正代码中的语法错误,如类定义中的__init__方法,正确的引号使用等。 5. 增加异常处理,确保在请求或解析失败时程序能优雅处理,避免崩溃。</think>以下是代码错误分析与修正方案: 🛠️ 主要错误分析: 1. JSON解析错误根源: - 正则表达式`re.findall('\(({.*})\)', html)[0]`匹配不准确 - 实际响应包含JSONP格式数据(如`jsonp_123456({...})`) - 未处理响应中的转义字符单引号 2. 语法规范问题: - 类初始化方法应为`def __init__(self, storename):` - URL字符串使用了中文引号‘’(应改为英文引号'或") - 未进行异常处理请求重试机制 ✅ 修正后的完整代码: ```python # -*- coding: utf-8 -*- import requests import json import csv import random import re from datetime import datetime import time class TMProducts: def __init__(self, storename): self.storename = storename self.url = f'https://{storename}.m.tmall.com' self.headers = { "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 " "(KHTML, like Gecko) Version/15.0 Mobile/15E148 Safari/604.1" } datenum = datetime.now().strftime('%Y%m%d%H%M') self.filename = f'{self.storename}_{datenum}.csv' self._init_csv() def _init_csv(self): """初始化CSV文件""" with open(self.filename, 'w', newline='', encoding='utf-8-sig') as f: writer = csv.DictWriter(f, fieldnames=[ 'item_id', 'price', 'quantity', 'sold', 'title', 'totalSoldQuantity', 'url', 'img' ]) writer.writeheader() def _get_json_data(self, html): """安全提取JSON数据""" try: # 改进正则表达式匹配 json_str = re.search(r'\(({.*?})\);?$', html, flags=re.DOTALL).group(1) # 处理非法字符 json_str = json_str.replace("'", '"').replace('\t', '') return json.loads(json_str) except (AttributeError, json.JSONDecodeError) as e: print(f"JSON解析失败: {str(e)}") print(f"原始响应内容:\n{html[:500]}...") # 打印前500字符用于调试 return None def get_totalpage(self): """获取总页数(含重试机制)""" retry = 3 while retry > 0: try: callback_num = random.randint(83739921, 87739530) url = f'{self.url}/shop/shop_auction_search.do?sort=s&p=1&page_size=12&from=h5&ajson=1&_tm_source=tmallsearch&callback=jsonp_{callback_num}' response = requests.get(url, headers=self.headers, timeout=10) response.encoding = 'utf-8' data = self._get_json_data(response.text) return int(data.get('total_page', 1)) if data else 1 except Exception as e: print(f"获取总页数失败: {str(e)}, 剩余重试次数: {retry-1}") retry -= 1 time.sleep(2) return 1 # 默认返回1页 def get_products(self, page): """获取单页商品数据""" try: callback_num = random.randint(83739921, 87739530) url = f'{self.url}/shop/shop_auction_search.do?sort=s&p={page}&page_size=12&from=h5&ajson=1&_tm_source=tmallsearch&callback=jsonp_{callback_num}' response = requests.get(url, headers=self.headers, timeout=10) response.encoding = 'utf-8' data = self._get_json_data(response.text) if data and data.get('items'): with open(self.filename, 'a', newline='', encoding='utf-8-sig') as f: writer = csv.DictWriter(f, fieldnames=[ 'item_id', 'price', 'quantity', 'sold', 'title', 'totalSoldQuantity', 'url', 'img' ]) # 数据清洗 cleaned_data = [] for item in data['items']: item['title'] = item.get('title', '').strip() item['price'] = float(item.get('price', 0)) cleaned_data.append(item) writer.writerows(cleaned_data) except Exception as e: print(f"第{page}页数据获取异常: {str(e)}") def main(self): """主运行方法""" total_page = self.get_totalpage() print(f"总页数: {total_page}") for page in range(1, total_page + 1): self.get_products(page) print(f"进度: {page}/{total_page} ({page/total_page:.1%})") time.sleep(random.uniform(1.5, 3.5)) # 更自然的间隔 if __name__ == '__main__': store = 'uniqlo' # 可替换目标店铺 crawler = TMProducts(store) crawler.main() ``` 🌟 主要改进点: 1. 增强正则表达式匹配: - 使用`re.DOTALL`标志匹配多行内容 - 改进模式匹配`r'\(({.*?})\);?$'` - 增加非法字符处理 2. 新增功能: - 请求重试机制(最多3次重试) - 数据清洗流程(处理价格、标题等字段) - 进度百分比显示 - 随机化请求间隔(1.5~3.5秒) 3. 异常处理: - 添加try-except块捕获网络异常 - JSON解析错误时打印原始响应内容 - 字段缺失时的默认值处理 4. 编码优化: - 使用`utf-8-sig`编码处理CSV文件 - 使用f-string格式化字符串 - 分离JSON解析逻辑到独立方法 ⚠️ 使用注意事项: 1. 遵守目标网站的robots.txt规则 2. 控制请求频率(当前设置为1.5-3.5秒/页) 3. 店铺名称需验证有效性(如uniqlo对应优衣库) 4. 可能需要处理动态加载内容(当前版本适用于基础数据抓取) 建议在运行前更新请求头中的User-Agent,并根据目标网站的最新结构调整数据解析逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值