网页抓取时如何使用 FindAll

How To Use FindAll While Web Scraping

我想抓取 https://www.ebay.co.uk/sch/i.html?_from=R40&_sacat=0&_nkw=xbox&_pgn=2&_skc=50&rt=nc 并获取磁贴(Microsoft Xbox 360 E 250 GB 黑色控制台、Microsoft Xbox One S 1TB 白色控制台和 2 个无线控制器等)。在适当的时候,我想为 Python 脚本提供不同的 eBay URLS,但是为了这个问题,我只想关注一个特定的 eBay URL。

然后我想将它们的标题添加到我将写入 Excel 的数据框中。我想我可以自己完成这部分。

没用 -

for post in soup.findAll('a',id='ListViewInner'):
    print (post.get('href'))

没用 -

for post in soup.findAll('a',id='body'):
      print (post.get('href'))

没用 -

for post in soup.findAll('a',id='body'):
   print (post.get('href'))

h1 = soup.find("a",{"class":"lvtitle"})
print(h1)

没用 -

for post in soup.findAll('a',attrs={"class":"left-center"}):
    print (post.get('href'))

没用 -

for post in soup.findAll('a',{'id':'ListViewInner'}):
    print (post.get('href'))

这给了我网页错误部分的链接,我知道 href 是超链接而不是标题,但我想如果下面的代码有效,我可以修改它的标题 -

for post in soup.findAll('a'):
    print (post.get('href'))

这是我的所有代码 -

import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile
import urllib.request
from bs4 import BeautifulSoup

#BaseURL, Syntax1 and Syntax2 should be standard across all
#Ebay URLs, whereas Request and PageNumber can change 

BaseURL = "https://www.ebay.co.uk/sch/i.html?_from=R40&_sacat=0&_nkw="

Syntax1 = "&_skc=50&rt=nc"

Request = "xbox"

Syntax2  = "&_pgn="

PageNumber ="2"

URL = BaseURL + Request + Syntax2 + PageNumber + Syntax1


print (URL)
HTML = urllib.request.urlopen(URL).read()

#print(HTML)

soup=b(HTML,"html.parser")

#print (soup)

for post in soup.findAll('a'):
    print (post.get('href'))

使用速度更快的 css 选择器。

import requests
from bs4 import  BeautifulSoup

url = 'https://www.ebay.co.uk/sch/i.html?_from=R40&_sacat=0&_nkw=xbox&_pgn=2&_skc=50&rt=nc'
Res = requests.get(url)
soup = BeautifulSoup(Res.text,'html.parser')
for post in soup.select("#ListViewInner a"):
    print(post.get('href'))

使用 format() 函数代替连接字符串。

import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile
import urllib.request
from bs4 import BeautifulSoup

BaseURL = "https://www.ebay.co.uk/sch/i.html?_from=R40&_sacat=0&_nkw={}&_pgn={}&_skc={}&rt={}"

skc = "50"
rt = "nc"
Request = "xbox"
PageNumber = "2"

URL = BaseURL.format(Request,PageNumber,skc,rt)
print(URL)
HTML = urllib.request.urlopen(URL).read()
soup = BeautifulSoup(HTML,"html.parser")
for post in soup.select('#ListViewInner a'):
    print(post.get('href'))