【问题标题】:How to search for a specific unicode string when web scraping?网页抓取时如何搜索特定的Unicode字符串?
【发布时间】:2019-08-23 01:25:05
【问题描述】:

我最近对 ​​Python 上的网页抓取感兴趣,并在一些简单的示例上做了,但我不知道如何处理其他不遵循 ASCII 代码的语言。例如,在 HTML 文件中搜索特定字符串或使用这些字符串写入文件。

from urllib.parse import urljoin
import requests
import bs4
website = 'http://book.iranseda.ir'
book_url = 'http://book.iranseda.ir/DetailsAlbum/?VALID=TRUE&g=209103'

soup1 = bs4.BeautifulSoup(requests.get(book_url).text, 'lxml')
match1 = soup1.find_all('a', class_='download-mp3')
for m in match1:
    m = m['href'].replace('q=10', 'q=9')
    url = urljoin(website, m)
    print(url)
    print()

book_url下的这个网站,每一行都有不同的文字,但是文字是波斯语的。 假设我需要考虑最后一行。 文字是“صدای کل کتاب” 如何在<li><div><a> 标签中搜索此字符串?

【问题讨论】:

  • 您希望返回什么?
  • 您在代码中的哪个位置尝试对波斯字符串进行此匹配?
  • 代码正在使用 Jack 提到的特定编码。

标签: python web-scraping beautifulsoup non-ascii-characters


【解决方案1】:

您需要将编码从requests 设置为UTF-8。看起来requests 模块没有使用您想要的解码。正如this SO post 中提到的,您可以告诉请求期望什么编码。

from urllib.parse import urljoin
import requests
import bs4
website = 'http://book.iranseda.ir'
book_url = 'http://book.iranseda.ir/DetailsAlbum/?VALID=TRUE&g=209103'

req = requests.get(book_url)
req.encoding = 'UTF-8'
soup1 = bs4.BeautifulSoup(req.text, 'lxml')
match1 = soup1.find_all('a', class_='download-mp3')
for m in match1:
    m = m['href'].replace('q=10', 'q=9')
    url = urljoin(website, m)
    print(url)
    print()

这里唯一的变化是

req = requests.get(book_url)
req.encoding = 'UTF-8'
soup1 = bs4.BeautifulSoup(req.text, 'lxml')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-02
    • 2018-09-25
    • 2012-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-12
    相关资源
    最近更新 更多