python美丽的汤进口网址

时间:2016-03-01 02:58:37

标签: python python-3.x web-scraping beautifulsoup

我正在尝试导入网址列表并抓住pn2和main1。我可以在不导入文件的情况下运行它,所以我知道它有效,但我不知道如何处理导入。这是我最近尝试过的,下面是网址的一小部分。提前谢谢。

import urllib
import urllib.request
import csv
from bs4 import BeautifulSoup

csvfile = open("ecco1.csv")
csvfilelist = csvfile.read()
theurl="csvfilelist"

soup = BeautifulSoup(theurl,"html.parser")
for row in csvfilelist:

    for pn in soup.findAll('td',{"class":"productText"}):
        pn2.append(pn.text)
    for main in soup.find_all('div',{"class":"breadcrumb"}):
        main1 = main.text

        print (main1)
        print ('\n'.join(pn2))

的url:     http://www.eccolink.com/products/productresults.aspx?catId=2458     http://www.eccolink.com/products/productresults.aspx?catId=2464     http://www.eccolink.com/products/productresults.aspx?catId=2435     http://www.eccolink.com/products/productresults.aspx?catId=2446     http://www.eccolink.com/products/productresults.aspx?catId=2463

1 个答案:

答案 0 :(得分:2)

从我看到的,您正在打开一个CSV文件并使用BeautifulSoup来解析它。 那应该不是那样的。 BeautifulSoup解析html文件,而不是CSV。

查看您的代码,如果您将html代码传递给Bs4,这似乎是正确的。

from bs4 import BeautifulSoup
import requests
links = []
file = open('links.txt')
html = requests.get('http://www.example.com')
soup = BeautifulSoup(html, 'html.parser')
for x in soup.find_all('a',"class":"abc"):
      links.append(x)
      file.write(x)
file.close()

上面是我如何在html代码中获取目标元素并将其写入文件/或将其附加到列表的非常基本的实现。使用请求而不是urllib。这是一个更好的图书馆,更现代化。

如果您想以CSV格式输入数据,我最好选择使用csv reader作为导入。

希望有所帮助。

相关问题