用python写一个程序: 利用Xpath,根据给定的人名,抽取百度百科人物的人物关系
时间: 2023-05-22 10:01:44 浏览: 63
以下是一个简单的Python程序,可以利用XPath从百度百科中抽取给定人名的人物关系:
```python
import requests
from lxml import etree
def get_relationship(name):
url = 'https://baike.baidu.com/item/' + name
response = requests.get(url)
html = response.text
tree = etree.HTML(html)
relationships = tree.xpath('//div[@class="lemma-summary"]/div[@class="para"]/a/text()')
return relationships
name = input('请输入人名:')
relationships = get_relationship(name)
print(name + '的人物关系:')
for relationship in relationships:
print(relationship)
```
请注意,这只是一个简单的示例程序,可能无法处理所有情况。如果您需要更复杂的功能,请考虑使用更高级的工具或库。
相关问题
用Python写一段代码,使用xpath 语法,爬取中关村手机网的所有手机型号
代码如下:from lxml import etree
import requestsurl = 'http://detail.zol.com.cn/cell_phone_index/subcate57_0_list_1_0_1_2_0_0.html'headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36'}response = requests.get(url, headers=headers)html = etree.HTML(response.text)# 使用xpath获取所有手机型号
phone_list = html.xpath("//div[@class='list-item']//div[@class='item-name']/a/text()")print(phone_list)
利用python爬取豆瓣音乐_Python爬虫:现学现用xpath爬取豆瓣音乐
好的,我可以为您提供相关的爬取豆瓣音乐的Python代码。以下是基于XPath的示例代码:
```python
import requests
from lxml import etree
url = 'https://music.douban.com/top250?start=0'
# 发送HTTP请求
response = requests.get(url)
# 解析HTML文档
html = etree.HTML(response.text)
# 使用XPath提取音乐名称和评分
musics = html.xpath('//div[@class="pl2"]/a/text()')
ratings = html.xpath('//span[@class="rating_nums"]/text()')
# 输出结果
for music, rating in zip(musics, ratings):
print(music, rating)
```
以上代码会爬取豆瓣音乐top250页面上的音乐名称和评分。您可以根据需要进一步完善代码,例如添加翻页功能,或者提取更多的音乐信息等。