当标题包含未转义的撇号 (') 时,如何使用 pywikibot.Page(site, title).text?

How do I use pywikibot.Page(site, title).text when the title has an unescaped apostrophe (')?

我有一个名为 cities 的字符串列表,其中每个字符串都是一个城市名称,也是维基百科页面的标题。对于每个城市,我都会获取维基百科页面,然后查看其中的文本内容:

cities = [(n["name"]) for n in graph.nodes.match("City")]
for city in cities:
       site = pywikibot.Site(code="en", fam="wikivoyage")
       page = pywikibot.Page(site, city)
       text = page.text

我列表中的一个城市是一个叫做 L'Aquila 的地方,它没有返回任何文本(而其他条目是)。我认为这是因为名称中的 '。所以我使用 re.sub 来转义 ' 并传入该结果。这给了我预期的结果:

cities = [(n["name"]) for n in graph.nodes.match("City")]
city = "L'Aquila"
altered_city = re.sub("'",  "\'", city)
print(altered_city)
site = pywikibot.Site(code="en", fam="wikivoyage")
page = pywikibot.Page(site, altered_city)
print(page)
print(page.text)

结果:

[[wikivoyage:en:L'Aquila]]
{{pagebanner|Pagebanner default.jpg}}
'''L'Aquila''' is the capital of the province of the same name in the region of [[Abruzzo]] in [[Italy]] and is located in the northern part of the..

但问题是我不想 hard-code 城市名称,我想使用列表中的字符串。当我传入它时,它没有给我 page.text:

的任何结果
cities = [(n["name"]) for n in graph.nodes.match("City")]
city_from_list = cities[0]
print(city_from_list)
print(type(city_from_list))
altered_city = re.sub("'",  "\'", city_from_list)
site = pywikibot.Site(code="en", fam="wikivoyage")
page = pywikibot.Page(site, altered_city)
print(page)
print(page.text)

结果:

L'Aquila
<class 'str'>
[[wikivoyage:en:L'Aquila]]

我打印出我从列表中获取的城市元素的值和类型,它是一个字符串,所以我不知道为什么它在上面起作用但在这里不起作用。它们有何不同?

re.sub("'", "\'", city) 什么都不做:

>>> city = "L'Aquila"
>>> re.sub("'",  "\'", city)
"L'Aquila"
>>> city == re.sub("'",  "\'", city)
True

Python 将 "\'" 视为 "'"。请参阅文档 Lexical analysis # String and Bytes literals 处的 table。

我不知道为什么代码的第二部分不适合你,但它应该。也许你只是没有执行最后一行。即使 page.text 返回了 None,打印语句也应该打印 None。试试 print(type(page.text)).

Pywikikbot 按预期为拉奎拉工作:例如

>>> import pywikibot
>>> site = pywikibot.Site('wikivoyage:en')
>>> page = pywikibot.Page(site, "L'Aquila")
>>> print(page.text[:100])
{{pagebanner|Pagebanner default.jpg}}
'''L'Aquila''' is the capital of the province of the same name

您的 cities[0] 似乎与 "L'Aquila" 不同。请注意 page.text 总是给出 str 而从不给出 return None。您可以使用 exists() 方法检查现有页面:

>>> page = pywikibot.Page(site, "L'Aquila")
>>> page.exists()
True
>>>