I'm now having a problem, this is the website i'm scraping : https://tw.dictionary.search.yahoo.com/search;_ylt=AwrtXGvbWIJibWYAFCp9rolQ;_ylc=X1MDMTM1MTIwMDM4MQRfcgMyBGZyA3NmcARmcjIDc2ItdG9wBGdwcmlkAwRuX3JzbHQDMARuX3N1Z2cDMARvcmlnaW4DdHcuZGljdGlvbmFyeS5zZWFyY2gueWFob28uY29tBHBvcwMwBHBxc3RyAwRwcXN0cmwDMARxc3RybAM0BHF1ZXJ5A3RhcGUEdF9zdG1wAzE2NTI3MDk5NTM-?p=take&fr2=sb-top&fr= sfp,它是雅虎提供的網路詞典,我要做的是當您輸入翻譯請求時,輸出將顯示結果。
import requests
from bs4 import BeautifulSoup
def searchdic():
global d
a = "https://tw.dictionary.search.yahoo.com/search;_ylt=AwrtXGvbWIJibWYAFCp9rolQ"
b = ";_ylc=X1MDMTM1MTIwMDM4MQRfcgMyBGZyA3NmcARmcjIDc2ItdG9wBGdwcmlkAwRuX3JzbHQDMARuX3N1Z2cDMARvcmlnaW4DdHcuZGljdGlvbmFyeS5zZWFyY2gueWFob28uY29tBHBvcwMwBHBxc3RyAwRwcXN0cmwDMARxc3RybAM0BHF1ZXJ5A3RhcGUEdF9zdG1wAzE2NTI3MDk5NTM-?"
c = "p="
e = "&fr2=sb-top&fr=sfp"
search = a b c d e
print(search)
resp = requests.get(search)
soup = BeautifulSoup(resp.text, 'html.parser')
#print(soup.find('','compList mb-25 p-rel'))
if soup.find('','compList mb-25 p-rel') == None:
print("Invalid query!")
else:
print(soup.find('div','compList mb-25 p-rel').text)
#divs = soup.find_all('div', 'compList mb-25 p-rel')
#for div in divs:
#print(f"{[s for s in div.stripped_strings]}""\n")
def changechinesetourl():
global d
from urllib import parse
str = d
d = parse.quote(str)
searchdic()
def is_contains_chinese():
global d
for _char in d:
if '\u4e00' <= _char <= '\u9fa5':
return True
return False
d = input("What do you want to translate: ")
is_contains_chinese()
if True:
changechinesetourl()
else:
searchdic()
這是我寫的,如果你輸入“take”,我的輸出會顯示:
佛特。拿,取;握,抱;拿,取走;奪取,奪走;抓,捕;吸引 vi. (染料)被吸收,染上;獲得財產 拍攝一次的電影)鏡頭[C]電影(電視量;接收量;收入)
我想看到是這樣分開的:
佛特。拿,取;握,抱;拿,取走;奪取,奪走;抓,捕;吸引
六。(染料)被吸收,染上;獲得財產
n. 拍攝一次的電影)鏡頭[C]電影(電視量;接收量;收入)
我試過用
#divs = soup.find_all('div', 'compList mb-25 p-rel')
#for div in divs:
#print(f"{[s for s in div.stripped_strings]}""\n")
但結果是相同的,但只有 [ 開頭和 ] 結尾。
我不確定是不是因為原始的 web html 沒有分行。
這是原始頁面代碼的一部分:
<div class="compList mb-25 p-rel" ><ul ><li class="lh-22 mh-22 mt-12 mb-12 mr-25"><div class=" pos_button fz-14 fl-l mr-12">vt.</div> <div class=" fz-16 fl-l dictionaryExplanation">拿,取;握,抱;拿走,取走;奪取,佔領;抓,捕;吸引</div> </li><li class="lh-22 mh-22 mt-12 mb-12 mr-25"><div class=" pos_button fz-14 fl-l mr-12">vi.</div> <div class=" fz-16 fl-l dictionaryExplanation">(染料)被吸收,染上;依法獲得財產</div> </li><li class="lh-22 mh-22 mt-12 mb-12 mr-25 last"><div class=" pos_button fz-14 fl-l mr-12">n.</div> <div class=" fz-16 fl-l dictionaryExplanation">一次拍攝的電影(電視)鏡頭[C];捕獲量;收穫量;收入[S1]</div>
uj5u.com熱心網友回復:
要按照您想要的方式格式化該文本,我必須這樣做:
for div in divs:
lis = div.find_all('li')
for li in lis:
print(li.text.replace('\n', ''))
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/476505.html
