我想考慮一下網站結構彎曲的情況,有很多相同的類和標簽。在這些類中,必要的資訊在不同的索引下,其中 [3],其中 [6]。哪里沒有。假設有:'Div' class = 'data-123'地址' Div 'class = 'data-123'資訊' Div 'class = 'data-123' Phone - 1234567890等這是我需要得到的電話。而在不同的卡片中,它的順序是隨機的,或者根本不存在。也就是說,它不會被xpath找到它,因為它每次都不一樣,選擇器可以與其他一些引數相同。也許在這門課上用“電話”這個詞?如何擺脫這種局面?
uj5u.com熱心網友回復:
要獲得公司頭銜和電話,您可以:
import requests
from bs4 import BeautifulSoup
url = "https://www.ua-region.com.ua/ru/kved/49.41"
soup = BeautifulSoup(requests.get(url).content, "html.parser")
for company in soup.select(".cart-company-lg"):
title = company.select_one(".cart-company-lg__title").text
telephones = [t.text for t in company.select('[href^="tel"]')]
print(title)
print(*telephones)
print("-" * 80)
印刷:
СПЕЦ-Ф-ТРАНС, ООО
38 (093) 7756...
...and so on.
編輯:從公司頁面獲取標題/電話:
import requests
from bs4 import BeautifulSoup
url = "https://www.ua-region.com.ua/ru/43434454"
soup = BeautifulSoup(requests.get(url).content, "html.parser")
sidebar = soup.select_one(".company-item-sidebar")
name = sidebar.select_one('span:-soup-contains("Юридическое название")')
name = name.find_next(text=True) if name else "N/A"
telephones = sidebar.select_one('span:-soup-contains("Телефоны")')
telephones = (
[a["href"] for a in telephones.find_next("div").find_all("a")]
if telephones
else []
)
# get other items here
# ...
print(name)
print(telephones)
print()
印刷:
Юридическое название
['tel: 380636540215', 'tel: 380685496792', 'tel: 380952052509']
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/529585.html
上一篇:如何從節點js/javascript中的回傳值中洗掉null或undefined
下一篇:格拉默左因子分解
