python-3.x - Python3:如何从 url 获取标题 eng?
问题描述
我用这个代码
import urllib.request
fp = urllib.request.urlopen("https://english-thai-dictionary.com/dictionary/?sa=all")
mybytes = fp.read()
mystr = mybytes.decode("utf8")
fp.close()
print(mystr)
x = 'alt'
for item in mystr.split():
if (x) in item:
print(item.strip())
我从这段代码中得到了泰语单词,但我不知道如何得到英文单词。谢谢
解决方案
如果你想从表中获取单词,你应该使用像BeautifulSoup4这样的解析库。这是一个如何解析这个的例子(我在这里使用请求来获取和beautifulsoup来解析数据):
首先在您的浏览器中使用开发工具识别您要解析的内容的表格。带有翻译的表具有servicesT
在整个文档中仅出现一次的类属性:
import requests
from bs4 import BeautifulSoup
url = 'https://english-thai-dictionary.com/dictionary/?sa=all;ftlang=then'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'lxml')
# Get table with translations
table = soup.find('table', {'class':'servicesT'})
之后,您需要获取包含泰语单词翻译的所有行。如果您查看页面的源文件,您会注意到前几<tr
行是仅包含标题的标题,因此我们将省略它们。之后,我们<td>
将从行中获取所有元素(在该表中始终有 3 个<td>
元素)并从中获取单词(在该表中,单词实际上嵌套在 and 中)。
table_rows = table.findAll('tr')
# We will skip first 3 rows beacause those are not
# contain information we need
for tr in table_rows[3:]:
# Finding all <td> elements
row_columns = tr.findAll('td')
if len(row_columns) >= 2:
# Get tag with Thai word
thai_word_tag = row_columns[0].select_one('span > a')
# Get tag with English word
english_word_tag = row_columns[1].find('span')
if thai_word_tag:
thai_word = thai_word_tag.text
if english_word_tag:
english_word = english_word_tag.text
# Printing our fetched words
print((thai_word, english_word))
当然,这是我设法从页面解析的非常基本的示例,您应该自己决定要抓取的内容。我还注意到表中的数据并非一直都有翻译,因此在抓取数据时应牢记这一点。您还可以使用Requests-HTML库来解析数据(它支持在您要抓取的页面上的表格中存在的分页)。
推荐阅读
- jenkins - 是否可以为 jenkins github 组织构建设置构建丢弃选项?
- javascript - 如何防止操作覆盖覆盖材料表中的可编辑 onRowAdd 按钮?
- python - 如何替换目录中每个文件中的字符串
- c# - 启用可靠会话时 WCF ContractFilter 不匹配
- ruby-on-rails - 参数数量错误 - resque
- java - 以编程方式提取方法的内容
- bash - 需要在linux中运行命令并通过grep查找结果
- php - PHP多维数组,将重复键合并成新数组
- javascript - Mediarecoder 派生的 mp4 缺少持续时间元数据
- ajax - 当单击按钮删除但数据无法删除且 url 未显示 id 时我遇到问题