To parse the HTML content you provided and convert it to JSON format using Python's parsel library, you can follow the steps below. This example will extract the city names and their corresponding links, organizing them into a structured JSON format.
First, make sure you have the parsel library installed. You can install it via pip if you haven't done so yet:
bash
pip install parsel
Here's a complete Python script to accomplish the task:
python
from parsel import Selector
import json
# Sample HTML content (shortened for demo purposes)
html_content = """
<body>
<div class="container">
<h1 class="mobtitle">移动手机号码段省市分类</h1>
<div class="row colbtm">
<div class="col-md-12">
<h4 class="page-head-line">直辖市</h4>
<div class="contentlist">
<ul class="col-md-12">
<li class="col-md-3"><a target="_blank" href="110100.html">北京</a></li>
<li class="col-md-3"><a target="_blank" href="310100.html">上海</a></li>
<li class="col-md-3"><a target="_blank" href="120100.html">天津</a></li>
<li class="col-md-3"><a target="_blank" href="500100.html">重庆</a></li>
</ul>
</div>
</div>
</div>
<div class="row colbtm">
<div class="col-md-12">
<h4 class="page-head-line">安徽省</h4>
<div class="contentlist">
<ul class="col-md-12">
<li class="col-md-1"><a target="_blank" href="340100.html">合肥</a></li>
<li class="col-md-1"><a target="_blank" href="340200.html">芜湖</a></li>
<li class="col-md-1"><a target="_blank" href="340300.html">蚌埠</a></li>
<li class="col-md-1"><a target="_blank" href="340400.html">淮南</a></li>
<li class="col-md-1"><a target="_blank" href="340500.html">马鞍山</a></li>
<li class="col-md-1"><a target="_blank" href="340600.html">淮北</a></li>
<li class="col-md-1"><a target="_blank" href="340700.html">铜陵</a></li>
</ul>
</div>
</div>
</div>
</div>
</body>
"""
# Parse the HTML content
selector = Selector(text=html_content)
# Initialize a dictionary to hold the results
results = {}
# Extract headings and corresponding cities
for section in selector.css('.row.colbtm'):
# Get the province name (section heading)
province = section.css('h4.page-head-line::text').get()
# Get cities under this province
cities = []
for li in section.css('li'):
city_name = li.css('a::text').get()
city_link = li.css('a::attr(href)').get()
cities.append({'name': city_name, 'link': city_link})
results[province] = cities
# Convert the results to JSON
json_output = json.dumps(results, ensure_ascii=False, indent=4)
# Print JSON output
print(json_output)
Explanation:
HTML Content: The sample HTML provided is stored in the variable html_content.
Selector: A Selector instance is created using the parsel library to parse the HTML content.
Extract Data: The script iterates through each section that contains a province and its cities, extracting the province name and the corresponding city names and links.
JSON Conversion: After gathering all the data in a dictionary format, json.dumps is used to convert the dictionary into a JSON-formatted string.
Output: Finally, the JSON string is printed, which will look like: