我想要这样的数据...

“基本球衣

它在锡上说了什么

主料:100%棉。”

在一个单元格中,但我正在获取这样的数据...

“基本骑行服在锡上的含义主要是:100%棉。”

这是HTML

<div class="about-me">
    <h4>ABOUT ME</h4>
    <span><div>Basic jersey</div><div>Does what it says on the tin</div><br>Main: 100% Cotton.</span>
</div>


这是我的密码

from selenium import webdriver
from lxml import html
import pandas as pd
import collections, os
from bs4 import BeautifulSoup

def Save_to_Csv(data):
    filename = 'data.csv'
    df = pd.DataFrame(data)
    df.set_index('Title', drop=True, inplace=True)
    if os.path.isfile(filename):
       with open(filename,'a') as f:
           df.to_csv(f, mode='a', sep=",", header=False, encoding='utf-8')
    else:
        df.to_csv(filename, sep=",", encoding='utf-8')

with open('urls.txt', 'r') as f:
        links = [link.strip() for link in f.readlines()]
driver = webdriver.Chrome()
for urls in links:
    global image
    driver.get(urls)
    source = driver.page_source
    tree = html.fromstring(source)
    data = BeautifulSoup(source, 'html.parser')
    imgtag = data.find_all('li', attrs={'class':'image-thumbnail'})
    image = []
    for imgsrc in imgtag:
        image.append(imgsrc.img['src'].replace('?$S$&wid=40&fit=constrain', '?$XXL$&wid=513&fit=constrain'))
    title = tree.xpath('string(.//div/h1)')
    price = tree.xpath('string(.//span[@class="current-price"])')
    sku = tree.xpath('string(.//div[@class="product-code"]/span)')
    aboutme = tree.xpath(('string(.//div[@class="about-me"]/span)'))

    foundings = collections.OrderedDict()
    foundings['Title'] = [title]
    foundings['Price'] = [price]
    foundings['Product_Code'] = [sku]
    foundings['Abouy_Me'] = [aboutme]
    foundings['Image'] = [image]
    Save_to_Csv(foundings)

    print title, price, sku, aboutme, image
driver.close()

最佳答案

使用给定的HTML,可以使用stripped_strings生成器解决此问题,如下所示:

from bs4 import BeautifulSoup

html = """
<div class="about-me">
    <h4>ABOUT ME</h4>
    <span><div>Basic jersey</div><div>Does what it says on the tin</div><br>Main: 100% Cotton.</span>
</div>"""

soup = BeautifulSoup(html, "html.parser")

print('\n'.join(soup.span.stripped_strings))


这将使每个组件进入剥离列表,然后将它们与换行符连接在一起:

Basic jersey
Does what it says on the tin
Main: 100% Cotton.

关于python - 将数据保存为新行,但保存在单个单元格lxml python中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51986817/

10-16 18:16