我编写此代码是为了从 Wikidata 获取所有第 1 代 Pokemon 的名称,然后我想将其转换为 SQL 表。
```python
sparql = SPARQLWrapper("https://query.wikidata.org/sparql")
sparql.setQuery("""
PREFIX wd: <http://www.wikidata.org/entity/>
PREFIX wdt: <http://www.wikidata.org/prop/direct/>
PREFIX wikibase: <http://wikiba.se/ontology#>
SELECT DISTINCT ?pokemon ?pokemonLabel
WHERE {
?pokemon wdt:P361 wd:Q3245450.
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE]". }
}""")
sparql.setReturnFormat(CSV)
result = sparql.query().convert()
pandas.read_csv(result).to_sql('PokemonDBP', conn, if_exists = 'replace', index = False)
```
但是,代码返回 ValueError、无效的文件路径或缓冲区对象类型:
我尝试重写代码以返回 JSON,然后创建一个循环来检查数据是否正确记录:
```python
sparql.setReturnFormat(JSON)
result = sparql.query().convert()
for res in result["results"]["bindings"]:
print(res["pokemonLabel"]["value"],
res["pokemon"]["value"])
```
但是,虽然其网站上的维基数据查询结果如下所示:
口袋妖怪 口袋妖怪标签
wd:Q2488577 穆克
wd:Q2739523 傀儡
...
这个循环的结果如下所示:
Q2485997 http://www.wikidata.org/entity/Q2485997
Q2486013 http://www.wikidata.org/entity/Q2486013
...
对于如何将此 SPARQL 查询的结果转换为 SQL 表的任何帮助和建议,我将不胜感激。
您可以解析请求中的html:
from requests_html import HTMLSession
from html.parser import HTMLParser
url ="https://m.wikidata.org/wiki/Q3245450"
session = HTMLSession()
r = session.get(url)
#print(len(r.html.absolute_links))
poke=[]
for e in r.html.absolute_links:
if 'https://m.wikidata.org/wiki/Q' in e and len(e) == 36:
poke.append(e)
def pok_char(url):
session = HTMLSession()
res = session.get(url)
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
if tag == 'meta' and ('property', 'og:title') in attrs:
print(attrs[1][1])
parser = MyHTMLParser()
parser.feed(res.text)
for li in poke:
pok_char(li)