Dan*_*hii 5 python beautifulsoup web-scraping
我正在尝试抓取产品的标题和价格。我面临一个问题,即网站的类有所不同。这是一个例子,
<a class="G-ab" href="thewebsite.com"><div class="G-l"><div class="G-m">Product Name</div></div><div class="G-k"><div>S$230</div><div>Product Description</div><div>Used</div></div></a>
Run Code Online (Sandbox Code Playgroud)
当我使用另一台计算机时,它会显示这个,
<a class="K-ab" href="thewebsite.com"><div class="K-l"><div class="K-m">Product Name</div></div><div class="K-k"><div>S$230</div><div>Product Description</div><div>Used</div></div></a>
Run Code Online (Sandbox Code Playgroud)
我意识到他们将课程更改为随机字母。我目前正在使用 BeautifulSoup4 并请求库。除了制作一整个很长的“if-elif”课程之外,还有什么方法可以获得课程?我试图抓取的网站是 carousell.com 我目前正在使用 lxml 解析器,如果这有帮助的话。感谢您的时间。
是的,@Bitto提到的是正确的。您可以使用正则表达式来识别唯一元素。使用re
您可以实现这一点。但是这是您的代码。您可以使用 pandasDataframe
来打印结果。
from bs4 import BeautifulSoup\nimport requests\nimport re\nimport pandas as pd\n\nhtml=requests.get("https://carousell.com/search/products/?cc_id=2195&query=I7&sort_by=time_created%2Cdescending")\nsoup=BeautifulSoup(html.text,"html.parser")\natag=soup.find_all(\'a\', class_=re.compile("-ab"))\nitemtitle=[]\nitemprice=[]\nfor a in atag:\n for title,price in zip(a.find_all(\'div\', class_=re.compile("-m")),a.find_all(\'div\', class_=re.compile("-k"))):\n itemtitle.append(title.text)\n itemprice.append(price.find(\'div\').text)\n\ndf=pd.DataFrame({"Title" :itemtitle, "Price" : itemprice})\nprint(df)\n
Run Code Online (Sandbox Code Playgroud)\n\n输出:
\n\n Price Title\n0 \xc2\xa3200 Acer Aspire Laptop (Used)\n1 \xc2\xa3700 MSI GP62 LEOPARD i7 12gb Ram windows 10\n2 \xc2\xa3120 Apple MacBook Pro\n3 \xc2\xa3155 iPhone 7 Plus\n4 \xc2\xa3155 Goophone I7 Plus\n5 \xc2\xa3579 MacBook Air 13.3inch 2014 i7 1.7GHz 8GB Ram 12...\n6 \xc2\xa3550 MacBook Pro 2016 16GB Ram\n7 \xc2\xa3600 CUSTOM GAMING/MEDIA PC COMPUTER\n8 \xc2\xa3900 MS I GE62 2QF-419UK APACHE/PRO TRUE FIRE POWER\n9 \xc2\xa3390 HP Envy 15 Intel Core i7 4000MQ 12GB Ram\n10 \xc2\xa3188 Goophone I7 Plus\n11 \xc2\xa3650 Apple IMac 27" i7 2.8Ghz Quad Core\n12 \xc2\xa3600 Custom Gaming Pc (Excellent Condition)\n13 \xc2\xa3499 iMac 21.5inch with wireless keyboard\n14 \xc2\xa31,299 MacBook Pro Retina 13 Inches AppleCare\n15 \xc2\xa3700 I7 4790k Water Cooled\n16 \xc2\xa3650 Gigabyte P15V2\n17 \xc2\xa3280 Two Monitors i7 PC\n18 \xc2\xa3250 Gaming laptop pro\n19 \xc2\xa31,000 MAC BOOK PRO 15 Ritna\n20 \xc2\xa3550 Apple MacBook Pro Laptop - A1286 15.2" 500 GB ...\n
Run Code Online (Sandbox Code Playgroud)\n
归档时间: |
|
查看次数: |
2052 次 |
最近记录: |