如何去除BeautifulSoup提取结果转换后的方括号?
解决输出中出现方括号的问题
问题根源:hun.select()方法返回的是匹配到的元素列表,直接对列表调用str()会输出列表的字符串表示(包含方括号和元素分隔符),这就是你看到[<span>Test</span>]的原因。
针对不同需求,有两种解决方式:
方式一:仅获取第一个匹配元素的HTML
如果目标是取第一个符合选择器的元素,用select_one()代替select(),它返回单个元素而非列表,转字符串后不会带方括号:
try: # 使用select_one获取单个匹配元素 description_elem = hun.select_one('#description > div.tab-pane-body > div > div > div > table') # 元素存在则转字符串,否则设为None description_str = str(description_elem) if description_elem else None except: description_str = None result = {"description": description_str} data.append(result) print(json2xml.Json2xml(data, wrapper="all", pretty=True, attr_type=False).to_xml())
方式二:拼接所有匹配元素的HTML
如果需要保留所有匹配到的元素,遍历元素列表,将每个元素转成字符串后拼接:
try: elements = hun.select('#description > div.tab-pane-body > div > div > div > table') # 拼接所有元素的HTML,可根据需求调整分隔符(比如用'\n'换行) description_str = ''.join(str(elem) for elem in elements) if elements else None except: description_str = None result = {"description": description_str} data.append(result) print(json2xml.Json2xml(data, wrapper="all", pretty=True, attr_type=False).to_xml())
内容的提问来源于stack exchange,提问作者Adrian
相关产品推荐
相关产品推荐

