抓取和字符串格式化问题:一次用 '' 抓取,另一次用 ""

Scraping and string-formatting issue : one time scrape with '' another time with ""

此代码:

    url="http://www.royalcanin.fr/nos-aliments/gammes-pour-chiens/tous-les-aliments-pour-chiens/les-aliments-chez-les-veterinaires/chiens-en-bonne-sante/small/chien-sterilise/neutered-adult-small-dog"## read URL from an array coming from an Url-CSV
#print(url)

page_0=urllib.request.urlopen(url)
soup_0 = BeautifulSoup(page_0.read(),"html.parser") 
restricted_webpage_title_indication= soup_0.find( "div", {"class":"bloc"} ) # to get title and indication
readable_restricted_title_indication=str(restricted_webpage_title_indication)
soup_title_indication=BeautifulSoup(readable_restricted_title_indication,"html.parser")

indication=[]


for li in soup_title_indication.find_all('li'):
    indication.append(li.get_text().strip())

Pair_indication=["Indications",indication]
print(Pair_indication)

给我以下打印:

['Indications', ['Risque de prise de poids', 'Sensibilité buccodentaire', "Risque de calculs d'oxalate et de struvite"]]

为什么最后一个元素用 " " 引号而不是像前两个元素那样用 ' ' 引号? 我在这里不明白的是,在网站上,三个 "li" 被标记并以相同的方式编写。像这样:

  • Risque de prize de poids
  • Sensibilité buccodentaire
  • Risque de calculs d'oxalate et de struvite
  • 为什么会这样?我错过了什么? 谢谢你的帮助 !

    你没有遗漏任何东西,Python 用双引号打印最后一个,因为该字符串的主体已经有单引号,所以不要用单引号打印并显示转义的内部单引号,Python 使用双引号打印该字符串。

    尽管列表的所有元素都是字符串,区别仅在于打印时。

    一个非常简单的例子来说明这一点 -

    >>> l = ['123','12\'3']
    >>> l
    ['123', "12'3"]
    >>> repr(l[1])
    '"12\'3"'
    >>> print(repr(l[1]))
    "12'3"
    

    请注意上面只是 repr() 处理它的方式,当写入 csv 时,csv 模块将以不同的方式正确处理它。示例 -

    >>> l = ['123','12\'3',"222'333"]
    >>> with open('b.csv','w') as f:
    ...     writer = csv.writer(f,quotechar="'")
    ...     writer.writerow(l)
    ...
    24
    >>> with open('b.csv','r') as f:
    ...     reader = csv.reader(f,quotechar="'")
    ...     for line in reader:
    ...             print(line)
    ...
    ['123', "12'3", "222'333"]
    []
    

    csv 文件看起来像 -

    123,'12''3','222''333'