最后的vessel_name元素好像不太对他是这样的你能帮我更新一下么departure_port:<div class="mds-text--medium-bold">Shanghai East Container Terminal</div>, departure_time :<div class="mds-text--medium-bold" data-test="departure-date">14 Jun 2023</div> arrival_port :<div class="mds-text--medium-bold">PSA Singapore Terminal</div> arrival_time: <div class="mds-text--medium-bold" data-test="arrival-date">25 Jun 2023</div>
时间: 2024-03-27 22:40:29 浏览: 150
抱歉,之前我的回答中`vessel_name`的选择器不正确。根据你提供的HTML代码,可以使用下面的代码来获取vessel_name:
```
vessel_name = soup.select_one("div:contains('Vessel Name') + div span").text.strip()
```
这个选择器使用了相邻兄弟选择器`+`和后代选择器`span`,匹配到Vessel Name标签后面的div元素中的span元素,并将其文本内容去除空格和换行符后存储在`vessel_name`变量中。
相关问题
departure_port:<div class="mds-text--medium-bold">Shanghai East Container Terminal</div>, departure_time :<div class="mds-text--medium-bold" data-test="departure-date">14 Jun 2023</div> arrival_port :<div class="mds-text--medium-bold">PSA Singapore Terminal</div> arrival_time: <div class="mds-text--medium-bold" data-test="arrival-date">25 Jun 2023</div> vessel_name :<span class="mds-text--medium-bold">NIMTOFTE MAERSK</span>你可以帮我把这些元素的索引更新到这段代码里面么soup = BeautifulSoup(response.text, "html.parser") for row in soup.select(".table-row"): departure_port = row.select_one(".departure-port").text.strip() departure_time = row.select_one(".departure-time").text.strip() arrival_port = row.select_one(".arrival-port").text.strip() arrival_time = row.select_one(".arrival-time").text.strip() vessel_name = row.select_one(".vessel-name").text.strip()
当然可以,你可以将代码更新如下:
```python
soup = BeautifulSoup(response.text, "html.parser")
for i, row in enumerate(soup.select(".table-row")):
departure_port = row.select_one(".departure-port").text.strip()
departure_time = row.select_one(".departure-time").text.strip()
arrival_port = row.select_one(".arrival-port").text.strip()
arrival_time = row.select_one(".arrival-time").text.strip()
vessel_name = row.select_one(".vessel-name").text.strip()
# 更新索引
departure_port_index = f"departure_port_{i}"
departure_time_index = f"departure_time_{i}"
arrival_port_index = f"arrival_port_{i}"
arrival_time_index = f"arrival_time_{i}"
vessel_name_index = f"vessel_name_{i}"
# 将每个元素的值存储到字典中
data_dict = {
departure_port_index: departure_port,
departure_time_index: departure_time,
arrival_port_index: arrival_port,
arrival_time_index: arrival_time,
vessel_name_index: vessel_name
}
# 将每个元素的索引和值打印出来
for key, value in data_dict.items():
print(f"{key}: {value}")
```
这样就可以将每个元素的索引更新为类似于`departure_port_0`、`departure_port_1`、`departure_port_2`等的形式,并将每个元素的索引和值存储到一个字典中,方便后续的使用。
vessel_name :<span class="mds-text--medium-bold">NIMTOFTE MAERSK</span>
如果`vessel_name`元素的HTML代码是`<span class="mds-text--medium-bold">NIMTOFTE MAERSK</span>`,那么使用下面的代码可以获取到它:
```
vessel_name = soup.select_one("span[class='mds-text--medium-bold']").text.strip()
```
这个选择器使用了属性选择器`[class='mds-text--medium-bold']`,匹配到class为`mds-text--medium-bold`的span元素,并将其文本内容去除空格和换行符后存储在`vessel_name`变量中。
阅读全文