Export data from BeautifulSoup to CSV

2019-08-21 08:49发布

[DISCLAIMER] I have been through plenty of the other answers on the area, but they do not seem to work for me.

I want to be able to export the data I have scraped as a CSV file.

My question is how do I write the piece of code which outputs the data to a CSV?

Current Code

import requests
from bs4 import BeautifulSoup 

url = "http://implementconsultinggroup.com/career/#/6257"
r = requests.get(url)

req = requests.get(url).text
soup = BeautifulSoup(r.content)
links = soup.find_all("a")

for link in links:
     if "career" in link.get("href") and 'COPENHAGEN' in link.text:
             print "<a href='%s'>%s</a>" %(link.get("href"), link.text)

Output from the code

View Position

</a>
<a href='/career/management-consultants-to-help-our-customers-succeed-with-
it/'>
Management consultants to help our customers succeed with IT
COPENHAGEN • At Implement Consulting Group, we wish to make a difference in 
the consulting industry, because we believe that the ability to create Change 
with Impact is a precondition for success in an increasingly global and 
turbulent world.




View Position

</a>
<a href='/career/management-consultants-within-process-improvement/'>
Management consultants within process improvement
COPENHAGEN • We are looking for consultants with profound
experience in Six Sigma, Lean and operational
management

Code I have tried

with open('ImplementTest1.csv',"w") as csv_file:
     writer = csv.writer(csv_file)
     writer.writerow(["link.get", "link.text"])
     csv_file.close()

Output in CSV format

Column 1: Url Links

Column 2: Job description

E.g

Column 1: /career/management-consultants-to-help-our-customers-succeed-with- it/

Column 2: Management consultants to help our customers succeed with IT COPENHAGEN • At Implement Consulting Group, we wish to make a difference in the consulting industry, because we believe that the ability to create Change with Impact is a precondition for success in an increasingly global and turbulent world.

1条回答
放荡不羁爱自由
2楼-- · 2019-08-21 09:00

Try this script and get the csv output:

import csv ; import requests
from bs4 import BeautifulSoup 

outfile = open('career.csv','w', newline='')
writer = csv.writer(outfile)
writer.writerow(["job_link", "job_desc"])

res = requests.get("http://implementconsultinggroup.com/career/#/6257").text
soup = BeautifulSoup(res,"lxml")
links = soup.find_all("a")

for link in links:
     if "career" in link.get("href") and 'COPENHAGEN' in link.text:
        item_link = link.get("href").strip()
        item_text = link.text.replace("View Position","").strip()
        writer.writerow([item_link, item_text])
        print(item_link, item_text)
outfile.close()
查看更多
登录 后发表回答