将网页中的数据放入列表(碎片)

2024-10-03 21:24:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个小机器人,它应该提供来自网站(ebay)的信息,并使用splinter和python放入一个列表中。我的第一行代码:

from splinter import Browser
with Browser() as browser:
url = "http://www.ebay.com"
browser.visit(url)
browser.fill('_nkw', 'levis')
button = browser.find_by_id('gh-btn')
button.click()

Ebay.com 如何使用网页中的信息将红色框中的信息列出?你知道吗

例如:[“Levi Strauss&;Co.513 Slim Straight Jean Ivory男式SZ”,12.99,0],[“Levi 501牛仔裤男式原版Levi Strauss牛仔直筒”,71.44,“Now”],[“Levis 501纽扣飞边牛仔裤收缩以适合多种尺寸”,[$29.99,$39.99]]


Tags: 代码browser信息url列表网站机器人button
2条回答

这不是一个完美的答案,但它应该起作用。 首先安装这两个模块 requestsBS4

pip install requests

pip install beautifulsoup4

import requests
import json
from bs4 import BeautifulSoup

#setting up the headers
headers={
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Referer': 'https://www.ebay.com/',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'en-US,en;q=0.8',
'Host': 'www.ebay.com',
'Connection': 'keep-alive',
'Cache-Control': 'max-age=0',
}
#setting up my proxy, you can disable it
proxy={
'https':'127.0.0.1:8888'
}

#search terms
search_term='armani'

#request session begins
ses=requests.session()

#first get home page so to set cookies
resp=ses.get('https://www.ebay.com/',headers=headers,proxies=proxy,verify=False)

#next get the search term page to parse request
resp=ses.get('https://www.ebay.com/sch/i.html?_from=R40&_trksid=p2374313.m570.l1313.TR12.TRC2.A0.H0.X'+search_term+'.TRS0&_nkw='+search_term+'&_sacat=0',
headers=headers,proxies=proxy,verify=False)


soup = BeautifulSoup(resp.text, 'html.parser')
items=soup.find_all('a', { "class" : "vip" })
price_items=soup.find_all('span', { "class" : "amt" })

final_list=list()

for item,price in zip(items,price_items):
    try:
        title=item.getText()
        price_val=price.find('span',{"class":"bold"}).getText()
        final_list.append((title,price_val))
    except Exception as ex:
        pass

print(final_list)

这是我得到的结果

enter image description here

我同意@Aki003,类似这样的说法

def get_links(ebay_url):
    page = requests.get(ebay_url).text
    soup = BeautifulSoup(page)
    links = []
    for item in soup.find_all('a'):
        links.append(item.get('href'))
    return(links)

你可以在网页上搜寻任何其他元素。查看beautifulsoup文档。你知道吗

相关问题 更多 >