[英]fetch all pages using python request, beautifulsoup
我試圖從 web 頁面獲取所有產品的名稱,但我只能有 12 個。如果我向下滾動 web 頁面,然后刷新並添加更多信息。 誰能告訴我如何獲取所有信息?
import requests
from bs4 import BeautifulSoup
import re
url = "https://www.outre.com/product-category/wigs/"
res = requests.get(url)
res.raise_for_status()
soup = BeautifulSoup(res.text, "lxml")
items = soup.find_all("div", attrs={"class":"title-wrapper"})
for item in items:
print(item.p.a.get_text())
你的代碼很好,東西在網站上,產品是動態加載的,所以當你提出請求時,你只能得到前 12 個產品。 您可以檢查瀏覽器中的開發者控制台以跟蹤瀏覽期間進行的 AJAX 調用。 我做到了,結果打電話給 URL 檢索更多產品
https://www.outre.com/product-category/wigs/page/2/
所以如果你想獲得瀏覽多個頁面所需的所有產品,我建議你使用循環並多次使用你的代碼
NB 您可以嘗試查看網站,看看是否有更方便的地方獲取產品(比如不是從主頁)
該頁面通過 JavaScript 加載來自不同 URL 的產品,因此beautifulsoup
看不到它。 要獲取所有頁面,您可以使用下一個示例:
import requests
from bs4 import BeautifulSoup
url = "https://www.outre.com/product-category/wigs/page/{}/"
page = 1
while True:
soup = BeautifulSoup(requests.get(url.format(page)).content, "html.parser")
titles = soup.select(".product-title")
if not titles:
break
for title in titles:
print(title.text)
page += 1
印刷:
...
Wet & Wavy Loose Curl 18″
Wet & Wavy Boho Curl 20″
Nikaya
Jeanette
Natural Glam Body
Natural Free Deep
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.